LeetCode – Symmetric Tree (Java)

Problem

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following is not:

    1
   / \
  2   2
   \   \
   3    3

Java Solution – Recursion

This problem can be solve by using a simple recursion. The key is finding the conditions that return false, such as value is not equal, only one node(left or right) has value.

public boolean isSymmetric(TreeNode root) {
	if (root == null)
		return true;
	return isSymmetric(root.left, root.right);
}
 
public boolean isSymmetric(TreeNode l, TreeNode r) {
	if (l == null && r == null) {
		return true;
	} else if (r == null || l == null) {
		return false;
	}
 
	if (l.val != r.val)
		return false;
 
	if (!isSymmetric(l.left, r.right))
		return false;
	if (!isSymmetric(l.right, r.left))
		return false;
 
	return true;
}

3 thoughts on “LeetCode – Symmetric Tree (Java)”

  1. private static boolean isSymmetric(Node a,Node b){
    if(a==null && b==null) return true;
    if(a==null || b==null) return false;
    return a.val==b.val && isSymmetric(a.left,b.right) && isSymmetric(a.right,b.left);
    }

  2. public class leet_func {
    String tree1 = “”;
    String tree2 = “”;
    public void PostOrder(TreeNode root){
    if(root == null){
    tree1 += null;
    return;
    }
    PostOrder(root.left);
    PostOrder(root.right);
    //System.out.println(root.val);
    tree1 += root.val;

    }

    public void reversePostOrder(TreeNode root){ //Reverse of post order to compare
    if(root == null){ //Comparison should give the same result.
    tree2+=null;
    return;
    }
    reversePostOrder(root.right);
    reversePostOrder(root.left);
    //System.out.println(root.val);
    tree2 += root.val;
    }

    public boolean isSymmetric(TreeNode root){
    PostOrder(root);
    reversePostOrder(root);
    System.out.println(tree1);
    System.out.println(tree2);

    //Comparison gives the same result. Draw the tree and check
    //PostOrder -> left -> right -> root
    //ReversePostOrder -> right -> left -> root

    if(tree1.equals(tree2)){
    return true;
    }else{
    return false;
    }
    }

    }

  3. Iterative solution. We will need two queue two store the left and right.

    if(root == null) return true;

    Queue left = new LinkedList();

    Queue right = new LinkedList();

    left.add(root.left);

    right.add(root.right);

    while(!left.isEmpty() && !right.isEmpty()){

    TreeNode l = left.remove();

    TreeNode r = right.remove();

    if(l == null && r == null) continue;

    else if(l == null || r == null) return false;

    if(l.val != r.val){

    return false;

    }

    else{

    left.add(l.left);

    left.add(l.right);

    right.add(r.right);

    right.add(r.left);

    }

    }

    return true;

Leave a Comment