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

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
 //注意:这个题与昨天的题思想有些不同。对于平衡树,要求树的每个节点都满足平衡的性质,即每个节点的左右子节点高度差都<=1
 //而这个题并不要求树的每个节点都满足对称性(否则就变相要求树必须是满树了),例如树{1 2 2 # 3 3 #}是对称树
public class Solution {
    public boolean subtreeSymmetric(TreeNode left_root,TreeNode right_root){      //判断两棵子树是否是对称的函数
        if(left_root==null && right_root==null) return true;
        if(left_root!=null && right_root==null) return false;
        if(left_root==null && right_root!=null) return false;       //子树是对称的条件是子树的根完全一样
                                                                    //此外,递归的比较左根的右子树与右根的左子树是否是对称的
        if(left_root.val != right_root.val) return false;           //以及左根的左子树与右根的右子树是否是对称的
        return subtreeSymmetric(left_root.left,right_root.right) && subtreeSymmetric(left_root.right,right_root.left);
    }
    
    public boolean isSymmetric(TreeNode root) {
        if(root == null) return true;
        if(root.left==null && root.right==null) return true;
        if(root.left!=null && root.right==null) return false;
        if(root.left==null && root.right!=null) return false;
        if(root.left.val != root.right.val) return false;          //一些基本的判断
        
        return subtreeSymmetric(root.left,root.right);             //逐级向下判断子树是否是对称的
    }
}







posted @ 2014-11-12 21:17  Mr.do  阅读(81)  评论(0编辑  收藏  举报