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.
Bonus points if you could solve it both recursively and iteratively.
Solution1:O(n)
public class Solution { public boolean isSymmetric(TreeNode root) { if(root==null)
return true; return isSymmetric(root.left,root.right); } public boolean isSymmetric(TreeNode a, TreeNode b){ if(a==null)
return b==null; if(b==null)
return false; if(a.val!=b.val)
return false;
return isSymmetric(a.left,b.right)&&isSymmetric(a.right,b.left);
} }
Solution2:O(n)
public class Solution { public boolean isSymmetric(TreeNode root) { if(root==null) return true; Queue<TreeNode> ql = new LinkedList<TreeNode>(); Queue<TreeNode> qr = new LinkedList<TreeNode>(); ql.add(root.left); qr.add(root.right); while(!ql.isEmpty() && !qr.isEmpty()){ TreeNode tmp1=ql.poll(); TreeNode tmp2=qr.poll(); if(tmp1==null &&tmp2!=null || tmp1!=null &&tmp2==null ) return false; if(tmp1 == null) continue; if(tmp1.val!=tmp2.val) return false; ql.add(tmp1.left); ql.add(tmp1.right); qr.add(tmp2.right); qr.add(tmp2.left); } return ql.isEmpty() && qr.isEmpty(); } }
Key Concept:Use Queue or traverse left and right
沒有留言:
張貼留言