对称二叉树
- https://leetcode.cn/problems/symmetric-tree/
描述
- 给你一个二叉树的根节点 root , 检查它是否轴对称。
示例 1
1/ | \2 | 2/ \ | / \3 4 | 4 3
中间一条线是对称轴
输入:root = [1,2,2,3,4,4,3]
输出:true
示例 2
1/ \
2 2\ \3 3
输入:root = [1,2,2,null,3,null,3]
输出:false
提示
- 树中节点数目在范围 [1, 1000] 内
- -100 <= Node.val <= 100
算法实现
1 )深度优先递归版本
/*** Definition for a binary tree node.* class TreeNode {* val: number* left: TreeNode | null* right: TreeNode | null* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {* this.val = (val===undefined ? 0 : val)* this.left = (left===undefined ? null : left)* this.right = (right===undefined ? null : right)* }* }*/function isSymmetric(root: TreeNode | null): boolean {if(!root) return true;const isMirror = (l: TreeNode | null, r: TreeNode | null) => {if(!l && !r) return true; // 空树是镜像的return l?.val === r?.val && isMirror(l?.left, r?.right) && isMirror(r?.left, l?.right)};return isMirror(root.left, root.right);
}
- 解题思路
- 转化为:左右子树是否镜像
- 分解为:树1的左子树和树2的左子树是否镜像;树1的右子树和树2的左子树是否镜像,成立,且根节点值相同,则镜像
- 符合:分、解、合的特性,考虑分而治之
- 解题步骤
- 分:获取两个树的左子树和右子树
- 解:递归地判断树1的左子树和树2的右子树是否镜像,树1的右子树和树2的左子树是否镜像
- 合:如果上述两个都成立,且根节点值也相同,两个树就是镜像
- 时间复杂度:O(n)
- 叶子节点数量
- 空间复杂度: O(n)
- 堆栈的高度,树的高度
- 最坏情况高度==树节点数
2 )广度优先迭代版本
/*** Definition for a binary tree node.* class TreeNode {* val: number* left: TreeNode | null* right: TreeNode | null* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {* this.val = (val===undefined ? 0 : val)* this.left = (left===undefined ? null : left)* this.right = (right===undefined ? null : right)* }* }*/function isSymmetric(root: TreeNode | null): boolean {if(!root || (!root.left && !root.right)) return true;const queue: (TreeNode | null)[] = [root.left, root.right];while(queue.length) {const left = queue.shift();const right = queue.shift();// 如果两个节点都为空就继续循环,两者有一个为空就返回falseif (!left && !right) continue;if (!left || !right) return false;if (left.val !== right.val) return false;// 将左节点的左孩子, 右节点的右孩子 存入队列queue.push(left.left);queue.push(right.right);// 将左节点的右孩子 和 右节点的左孩子 存入队列queue.push(left.right);queue.push(right.left);}return true;
}
- 使用广度优先遍历来替代深度优先遍历实现对称校验
- 时间复杂度是 O(n)
- 空间复杂度是 O(n)