[leetcode]Symmetric Tree

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.

算法思路:

思路:递归。镜像判断。

代码如下:

 1 public class Solution {
 2     public boolean isSymmetric(TreeNode root) {
 3         if(root == null || (root.left == null && root.right == null)) return true;
 4         return isSym(root.left, root.right);
 5             
 6         
 7     }
 8     public boolean isSym(TreeNode left,TreeNode right){
 9         if(left == null && right == null) return true;
10         if((left == null && right != null) || (left != null && right == null) || right.val != left.val) 
         return false; 11 return isSym(left.left, right.right) && isSym(left.right, right.left); 12 } 13 }

 

posted on 2014-07-31 19:53  喵星人与汪星人  阅读(163)  评论(0编辑  收藏  举报