//给你一个二叉树的根节点 root , 检查它是否轴对称。
//
//
//
// 示例 1:
//
//
//输入:root = [1,2,2,3,4,4,3]
//输出:true
//
//
// 示例 2:
//
//
//输入:root = [1,2,2,null,3,null,3]
//输出:false
//
//
//
//
// 提示:
//
//
// 树中节点数目在范围 [1, 1000] 内
// -100 <= Node.val <= 100
//
//
//
//
// 进阶:你可以运用递归和迭代两种方法解决这个问题吗?
//
// Related Topics 树 深度优先搜索 广度优先搜索 二叉树 👍 2666 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
/**
* 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) {
/* 如果一个树的左子树与右子树镜像对称,那么这个树是对称的。
因此,该问题可以转化为:两个树在什么情况下互为镜像?即:
如果同时满足下面的条件,两个树互为镜像:
1 它们的两个根结点具有相同的值
2 每个树的右子树都与另一个树的左子树镜像对称
*/
return check(root.left, root.right);
}
private boolean check(TreeNode root1, TreeNode root2) {
if (root1 == null && root2 == null) {
return true;
}
if (root1 == null || root2 == null) {
return false;
}
if (root1.val != root2.val) {
return false;
}
return check(root1.left, root2.right) && check(root1.right, root2.left);
}
}
//leetcode submit region end(Prohibit modification and deletion)
24 easy 101. 对称二叉树
于 2024-03-09 23:21:39 首次发布