[LeetCode] 101. Symmetric Tree Java

题目:

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following [1,2,2,null,3,null,3] 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) {
        if(root==null) return true;
        return isSymmetricTwo(root.left,root.right);
    }

    public boolean isSymmetricTwo(TreeNode node1,TreeNode node2){
        if((node1!=null&&node2==null)||(node1==null&&node2!=null)) return false;        //一边有一遍没有那么直接返回false
        if(node1==null&&node2==null) return true;
        if(node1.val==node2.val)
            return isSymmetricTwo(node1.left,node2.right)&&isSymmetricTwo(node1.right,node2.left);
        return false;
    }
}

 

  

 

posted @ 2017-07-17 09:56  荒野第一快递员  阅读(228)  评论(0编辑  收藏  举报