对称二叉树(Symmetric Tree)
LeetCode传送门101. Symmetric Tree
题目
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
给定一个二叉树,检查它是否是镜像对称的。
Example:
Input: root = [1,2,2,3,4,4,3]
Output: true
Input: root = [1,2,2,null,3,null,3]
Output: false
Constraints:
The number of nodes in the tree is in the range [1, 1000]. -100 <= Node.val <= 100
Follow up: Could you solve it both recursively and iteratively?
思考线
解题思路
可以递归遍历根节点的左右子树,检查左子树的左节点是否和右子树的右节点相等,右节点的左子树和左节点的右子树是否相等即可。
代码如下
function isSymmetric(root: TreeNode | null): boolean {
if (!root) return true;
return isS(root.left, root.right)
};
function isS(a, b) {
if (!a && !b) return true;
if (!a && b || !b && a) return false;
if (a.val !== b.val) return false;
return isS(a.left, b.right) && isS(a.right, b.left);
}
同样我们也可以用迭代的方式实现相同的功能
function isSymmetric(root: TreeNode | null): boolean {
if (!root) return true;
const stack = [root.left, root.right]
while (stack.length) {
const l = stack.shift();
const r= stack.shift();
if (!l && !r) continue;
if (!l && r || !r && l) return false;
if (l.val !== r.val) return false;
stack.push(l.left)
stack.push(r.right)
stack.push(r.left)
stack.push(l.right)
}
return true;
};
这就是我对本题的解法,如果有疑问或者更好的解答方式,欢迎留言互动。