【算法训练】LeetCode#101 对称二叉树
一、描述
101. 对称二叉树
给你一个二叉树的根节点 root
, 检查它是否轴对称。
示例 1:
输入:root = [1,2,2,3,4,4,3]
输出:true
示例 2:
输入:root = [1,2,2,null,3,null,3]
输出:false
二、思路
- 就是一道考察二叉树遍历的简单难度的算法题,可以用循环迭代或是递归来做。
三、解题
public static 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;
}
}
public static class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null){
return true;
}
if (root.left == root.right && root.left == null){
// 子节点都为空
return true;
} else if (root.left == null || root.right == null){
// 存在一个null一个不null
return false;
}
Queue<TreeNode> leftTree = new LinkedList<>();
leftTree.add(root.left);
Queue<TreeNode> rightTree = new LinkedList<>();
rightTree.add(root.right);
while (!leftTree.isEmpty() && !rightTree.isEmpty()){
if (leftTree.peek().val != rightTree.peek().val){
return false;
}
// 如果对称位置的节点val相同
TreeNode left = leftTree.poll();
TreeNode right = rightTree.poll();
if ((left.left == null || right.right == null) && left.left != right.right){
// 有一个节点为null,另一个不为null,一定不对称
return false;
}
if ((left.right == null || right.left == null) && left.right != right.left){
// 有一个节点为null,另一个不为null,一定不对称
return false;
}
// 只入队非空节点,且顺序为,左树的左右节点,右树的右左节点
if (left.left != null){
leftTree.add(left.left);
}
if (left.right != null){
leftTree.add(left.right);
}
if (right.right != null){
rightTree.add(right.right);
}
if (right.left != null){
rightTree.add(right.left);
}
}
return true;
}
// 递归写法
public boolean isSymmetricV2(TreeNode root) {
if (root == null){
return true;
}
return process(root.left,root.right);
}
// 对于每一次调用,都是在比较左右和右左
public boolean process(TreeNode left,TreeNode right){
if (left == null && right == null){
return true;
} else if(left == null || right == null){
return false;
}
if (left.val == right.val){
return process(left.left,right.right) && process(left.right,right.left);
} else {
return false;
}
}
}