题目
思路
判断树是否对称,那么就是判断根结点root
的两个子树root.left
和root.right
是否对称。
将特殊情况进行额外处理:
如根结点为空,根结点没有左右子树,那么也是对称二叉树,返回true
解决完特殊情况以后,那么就判断根结点的左右子树是否对称
假设根结点root的左子树的根结点为root1
,根结点root的右子树的根结点为root2
那么就对这两个子树进行判断
判断
root1.left==root2.right?
root1.right==root2.left?
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
//根结点为空
if(root==null)
return true;
//根结点没有左右子树
if(root.right==null && root.left==null)
return true;
if(root.right!=null && root.left!=null){
//判断根结点的左右子树是否对称
return judge(root.left,root.right);
}
return false;
}
public boolean judge(TreeNode root1,TreeNode root2)
{
if(root1.val!=root2.val)
return false;
boolean flag1=true; //记录左子树的left是否与右子树的right相等
boolean flag2=true; //记录左子树的right是否与右子树的left相等
//一边为空一边不为空,则肯定非对称
if(root1.left==null && root2.right!=null || root1.left!=null && root2.right==null
|| root1.right==null && root2.left!=null || root1.right!=null && root2.left==null)
return false;
//判断左子树的left是否与右子树的right相等
if(root1.left!=null && root2.right!=null){
flag1=judge(root1.left,root2.right);
}
//判断左子树的right是否与右子树的left相等
if(root1.right!=null && root2.left!=null){
flag2=judge(root1.right,root2.left);
}
return (flag1&&flag2);
}
}
更新:
class Solution {
public boolean isSymmetric(TreeNode root) {
//根节点无需判断左右对称,因此在这里就进行处理
if(root==null){
return true;
}
//判断左右子树是否对称,函数中递归进行判断
return judge(root.left,root.right);
}
public boolean judge(TreeNode rootLeft,TreeNode rootRight){
if(rootLeft==null && rootRight==null) {
return true;
}
//有一者为空,则为false
if(rootLeft==null || rootRight==null){
return false;
}
//当前左右子树非对称的话,直接返回false,不再深入下一层
if(rootLeft.val!=rootRight.val){
return false;
}else{
//深入下一层
return judge(rootLeft.left,rootRight.right) && judge(rootLeft.right,rootRight.left);
}
}
}