Skip to content

Latest commit

 

History

History
71 lines (62 loc) · 1.79 KB

101. Symmetric Tree.md

File metadata and controls

71 lines (62 loc) · 1.79 KB

#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 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.

思路:递归思路,左节点和右节点的数值相同。

Java Solution(Recurive)

public class Solution {
    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;
        if((l!=null&&r==null)||(l==null&&r!=null))return false;
        if(l.val!=r.val)return false;
        return (l.val==r.val)&&isSymmetric(l.left,r.right)&&isSymmetric(l.right,r.left);
    }
}

Java Solution(Iterative)

public class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root==null) return true;
        Queue<TreeNode> q1 = new LinkedList<TreeNode>(),q2 = new LinkedList<TreeNode>();
        q1.add(root.left);
        q2.add(root.right);
        while(!q1.isEmpty&&!q2.isEmpty){
            if(q1.size!=q2.size) return false;
            for(int i=0;i<q1.size;i++){
                TreeNode t1 = q1.remove();
                TreeNode t2 = q2.remove();
                if(t1==null&&t2==null) continue;
                if(t1!=null||t2!=null) return false;
                if(t1.val!=t2.val) return false;
                q1.add(t1.left);
                q1.add(t1.right);
                q2.add(t2.right);
                q2.add(t2.left);
            }
        }
        return q1.isEmpty()&&q2.isEmpty();
    }
}