对称二叉树
唯爱编程 人气:0题目
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树[1,2,2,3,4,4,3]
是对称的。
1
/ \
2 2
/ \ / \
3 4 4 3
但是下面这个[1,2,2,null,3,null,3]
则不是镜像对称的:
1
/ \
2 2
\ \
3 3
解法
解法一: 递归。
/**
* 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;
}
TreeNode left = root.left;
TreeNode right = root.right;
return isSymmetricForLeftAndRight(left,right);
}
// 判断left和right是否对称
public boolean isSymmetricForLeftAndRight(TreeNode left,TreeNode right){
if(left == null || right == null){
if(left != null || right != null){
return false;
} else {
return true;
}
}
// 判断值是否相等
int leftVal = left.val;
int rightVal = right.val;
if(leftVal != rightVal){
return false;
}
// 递归调用,判断左节点的左节点与右节点的右节点是否对称
TreeNode leftNextLeft = left.left;
TreeNode rightNextRight = right.right;
if(!isSymmetricForLeftAndRight(leftNextLeft,rightNextRight)){
return false;
}
// 递归调用,判断左节点的右节点与右节点的左节点是否对称
TreeNode leftNextRight = left.right;
TreeNode rightNextLeft = right.left;
if(!isSymmetricForLeftAndRight(leftNextRight,rightNextLeft)){
return false;
}
return true;
}
}
解法二: 迭代。
/**
* 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;
}
// 创建队列,特点是先进先出。
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root.left);
queue.offer(root.right);
while(!queue.isEmpty()){
TreeNode left = queue.poll();
TreeNode right = queue.poll();
if(left == null || right == null){
if(left != null || right != null){
return false;
} else {
continue;
}
}
int leftVal = left.val;
int rightVal = right.val;
if(leftVal != rightVal){
return false;
}
// 再把left和right子节点放进去,注意顺序
// 顺序一定是left的左节点和right的右节点,然后是left的右节点和right的左节点
queue.offer(left.left);
queue.offer(right.right);
queue.offer(left.right);
queue.offer(right.left);
}
return true;
}
}
总结
本篇文章讲解了算法题目的思路和解法,代码和笔记由于纯手打,难免会有纰漏,如果发现错误的地方,请第一时间告诉我,这将是我进步的一个很重要的环节。以后会定期更新算法题目以及各种开发知识点,如果您觉得写得不错,不妨点个关注,谢谢。
加载全部内容