您的位置:首页 > 编程语言 > Java开发

【leetcode】【101】Symmetric Tree

2016-03-04 10:38 507 查看

一、问题描述

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

二、问题分析

无非还是树的遍历问题。只不过与传统的先序、中序、后序、层次等不太一样。首先空树符合条件,只有根节点也符合,然后判断根节点的左孩子和右孩子,然后递归遍历。需要注意的是,递归的node的左右。

三、Java AC代码

public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
return isSymmetricTree(root.left, root.right);
}

public boolean isSymmetricTree(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
}
if (p == null || q == null) {
return false;
}
return p.val == q.val && isSymmetricTree(p.left, q.right)
&& isSymmetricTree(p.right, q.left);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java leetcode tree