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

判定一棵树是不是对称的,和 Same Tree这道题思想一样,same tree是判断两个数是不是一样,这道题目是判断左子树是不是右子树的镜像,用递归解决。代码如下:
/**
 * 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 isSym(root.left, root.right);
    }
    public boolean isSym(TreeNode leftNode, TreeNode rightNode) {
        if(leftNode == null && rightNode == null) return true;
        if(leftNode != null && rightNode != null) {
            if(leftNode.val != rightNode.val) return false;
            return isSym(leftNode.left, rightNode.right) && isSym(leftNode.right, rightNode.left);
        }
        return false;
    }
}

猜你喜欢

转载自kickcode.iteye.com/blog/2276050