[leedcode 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
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isSymmetric(TreeNode root) {
        /*本题题意验证一个二叉树是不是镜像的,使用递归思想
        如果两个根节点相等,递归验证镜像的对应部分isSymm(left.left,right.right)&&isSymm(left.right,right.left);
        注意自定义函数的意义:两个参数,代表镜像的两个对应点
        */
        if(root==null) return true;
        return isSymm(root.left,root.right);
    }
    public boolean isSymm(TreeNode left,TreeNode right){
        /*if(left==null) return right==null?true:false;
        if(right==null) return false;
        */
        if(left==null&&right==null) return true;
        if(left==null||right==null) return false;
        if(left.val==right.val){
            return isSymm(left.left,right.right)&&isSymm(left.right,right.left);
        }
        return false;
    }
}

 

posted @ 2015-07-20 16:59  ~每天进步一点点~  阅读(115)  评论(0编辑  收藏  举报