题目描述:
给你一个二叉树的根节点 root
, 检查它是否轴对称。
示例 1:
输入:root = [1,2,2,3,4,4,3] 输出:true
示例 2:
输入:root = [1,2,2,null,3,null,3] 输出:false
非递归Java代码:
/**
* 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.left==null || root.right==null){//判断根节点左右子树是否都为空
return root.left==null && root.right==null;//左右子树都为空,返回true,其中有一个不为空,返回false
}
TreeNode n1=root.right;
TreeNode n2=root.left;
List<TreeNode> list1=new LinkedList<>();//根节点的右子树的遍历集合
List<TreeNode> list2=new LinkedList<>();//根节点的左子树的遍历集合
list1.add(n1);
list2.add(n2);
while(list1.size()!=0 && list2.size()!=0){//两个集合都不为空
TreeNode index1=list1.get(0);//取出列表首部
TreeNode index2=list2.get(0);
list1.remove(0);
list2.remove(0);
if(index1.val!=index2.val){
return false;
}else{
if(index1.left!=null && index2.right!=null){//对称判断
list1.add(index1.left);
list2.add(index2.right);
}else if(index1.left!=null || index2.right!=null){
return false;
}
if(index1.right!=null && index2.left!=null){
list1.add(index1.right);
list2.add(index2.left);
}else if(index1.right!=null || index2.left!=null){
return false;
}
}
}
if(list1.size()!=0 || list2.size()!=0){//结果中有一个集合不为空,说明不对称
return false;
}else{
return true;
}
}
}
递归Java代码:
/**
* 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.left==null || root.right==null){//判断根节点左右子树是否都为空
return root.left==null && root.right==null;//左右子树都为空,返回true,其中有一个不为空,返回false
}
return isFait(root.right,root.left);
}
public boolean isFait(TreeNode right,TreeNode left){
if(left==null || right==null){//判断根节点左右子树是否都为空
return left==null && right==null;//左右子树都为空,返回true,其中有一个不为空,返回false
}
if(right.val!=left.val){
return false;
}
return isFait(right.right,left.left)&& isFait(right.left,left.right);
}
}