101 Symmetric Tree

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

For example, this binary tree[1,2,2,3,4,4,3]is symmetric:

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

But the following[1,2,2,null,3,null,3]is not:

    1
   / \
  2   2
   \   \
   3    3

Note:
Bonus points if you could solve it both recursively and iteratively.

Solution)

Iterative approach

class Solution {
    public boolean isSymmetric(TreeNode root) {
        if (root == null || (root.left == null && root.right == null)) return true;
        Queue<TreeNode> lq = new LinkedList<>();
        Queue<TreeNode> rq = new LinkedList<>();
        lq.add(root.left);
        rq.add(root.right);
        while (lq.size() != 0 && rq.size() != 0 && lq.size() == rq.size()) {
            while(!lq.isEmpty() && !rq.isEmpty()) {
                TreeNode left = lq.remove();
                TreeNode right = rq.remove();
                if ((left != null && right == null) ||
                    (left == null && right != null)) return false;
                if (left != null && right != null) {
                    if (left.val != right.val) return false;
                    lq.add(left.left);
                    lq.add(left.right);
                    rq.add(right.right);
                    rq.add(right.left);
                }
            }
        }
        return lq.size() == rq.size();
    }
}

Recursive approach

class Solution {
    public boolean helper(TreeNode left, TreeNode right) {
        if (left == null || right == null) return left == right;
        return left.val == right.val && helper(left.left, right.right) && helper(left.right, right.left);
    }
    public boolean isSymmetric(TreeNode root) {
        return root == null || helper(root.left, root.right);
    }
}

results matching ""

    No results matching ""