一、题目
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
二、思路及代码实现
思路:
先求出这棵二叉树对应的镜像树,然后逐个比较两棵树的节点。都可以递归实现。
参考代码:
public class Solution {
boolean isSymmetrical(TreeNode pRoot){
if(pRoot == null)
return true;
TreeNode mirror = mirror(pRoot);
return isSymmetrical(pRoot, mirror);
}
public boolean isSymmetrical(TreeNode root, TreeNode mirror){
// 注意这里对空树的两种处理情况
if(root == null && mirror == null){
return true;
}else if(root == null || mirror == null){
return false;
}
if(root.val == mirror.val)
return isSymmetrical(root.left, mirror.left) && isSymmetrical(root.right, mirror.right);
return false;
}
// 求一棵二叉树的镜像树
public TreeNode mirror(TreeNode root){
if(root == null)
return null;
TreeNode newRoot = new TreeNode(root.val);
newRoot.left = mirror(root.right);
newRoot.right = mirror(root.left);
return newRoot;
}
}