您的位置:首页 > 其它

[leetcode]Symmetric Tree

2015-12-11 11:20 323 查看
题目描述如下:

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

For example, this binary tree is symmetric:



But the following is not:



判断一棵树是否为对称的

一般树的题目本人喜欢用递归实现,在每个子树中考虑以下几种情况:

1、一棵树是否对称与根节点无关,而与左右节点有关,所以接下来的判断都是针对两个节点;

2、如果左右节点都为空,返回true;

3、若两个节点只有一边为空,返回false;

4、若两个节点值相等,返回true;

5、若两个节点值不相等,递归判断左节点的右子树与右节点的左子树是否相等以及左节点的左子树和右节点的右子树是否相等

题中的案例是一个不粗的提示可以判别算法是否正确。代码如下:

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

public boolean jugdement(TreeNode node1, TreeNode node2){
if(node1 == null && node2 == null) return true;
else if(node1 == null || node2 == null) return false;

if(node1.val != node2.val) return false;
else return jugdement(node1.left, node2.right) && jugdement(node1.right, node2.left);
}
}


题目链接:https://leetcode.com/problems/symmetric-tree/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: