Tuesday, February 11, 2014

Symmetric Tree

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
Note:
Bonus points if you could solve it both recursively and iteratively.
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

Solution:
Compare it level by level.
And use to stacks to represent its left and right child. 

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root == null) return true;
        Stack s1 = new Stack();
        Stack s2 = new Stack();
        s1.push(root.left);
        s2.push(root.right);
        while(!s1.isEmpty() && !s2.isEmpty()){
            TreeNode tr1 = s1.pop();
            TreeNode tr2 = s2.pop();
            if((tr1 == null) && (tr2 == null)) continue;
            if((tr1 == null) || (tr2 == null)) return false;
            if(tr1.val != tr2.val) return false;
            s1.push(tr1.left);
            s1.push(tr1.right);
            s2.push(tr2.right);
            s2.push(tr2.left);
        }
        return true;
    }
}

No comments:

Post a Comment