力扣-101. 对称二叉树
题目大意
给定一颗二叉树,判断是否对称
解题思路
将其中一个子树镜像翻转,再判断左右子树相不相等即可。镜像翻转示意图如下:
code
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
if(root==null)
return true;
TreeNode leftTree = mirrorTree(root.left); # 将左子树翻转
return isEqualTo(leftTree,root.right); # 判断子树是否相等
}
public TreeNode mirrorTree(TreeNode root) {
if(root==null){
return root;
}
if(root.left==null&&root.right==null){# 当前节点为叶子节点时,返回
return root;
}
TreeNode pre = root.left;# 保存左子树
root.left = mirrorTree(root.right); #令左子树等于翻转后的右子树
root.right = mirrorTree(pre); # 令右子树等于翻转后的左子树
return root;
}
public boolean isEqualTo(TreeNode left, TreeNode right){
if(left==null&&right==null) # 当其父节点为叶子节点时,返回true
return true;
if(left==null || right== null) #当某一子树为空时,返回false
return false;
if(left.val!=right.val)
return false;
return (isEqualTo(left.left,right.left) && isEqualTo(left.right,right.right));
}
}