题目:
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
解题思路:
对称二叉树的特点是抽对称,因此可以设置一种遍历方式,从而对比两种遍历方式即可看出来,前序遍历为根、左、右,可以定义一种新的遍历方式,根、右、左,即对称前序遍历。
代码:
//前序遍历和对称前序遍历对比来判断
public boolean isSymmetrical(TreeNode pRoot){
if (pRoot == null) {
return true;
}
return helper(pRoot.left, pRoot.right);
}
private boolean helper(TreeNode root1, TreeNode root2) {
if (root1 == null && root2 == null) {
return true;
}
if (root1 == null || root2 == null) {
return false;
}
if (root1.val != root2.val) {
return false;
}
return helper(root1.left, root2.right) && helper(root1.right, root2.left);
}
------------EOF-----------