101. 对称二叉树
题目来源:101. 对称二叉树
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [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. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {boolean} */ var isSymmetric = function(root) { var check = (left, right) => { if(!left && !right){ return true } if(!left || !right){ return false } return left.val === right.val && check(left.left, right.right) && check(left.right, right.left) } if(!root){ return true } return check(root, root) }; var isSymmetric = function(root) { var check = (left, right) => { let stackL = [] let stackR = [] stackL.push(left) stackR.push(right) while(stackL.length){ let l = stackL.shift() let r = stackR.shift() if(!l && !r){ continue } if((!l || !r) || (l.val !== r.val)){ return false } stackL.push(l.left) stackL.push(l.right) stackR.push(r.right) stackR.push(r.left) } return true } return check(root, root) };
Python3
# Definition for a binary tree node. from _typeshed import SupportsReadline class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def isSymmetric(self, root: TreeNode) -> bool: def check(l, r): if not l and not r: return True if not l or not r: return False return (l.val == r.val) and check(l.left, r.right) and check(l.right, r.left) return check(root, root) class Solution: def isSymmetric(self, root: TreeNode) -> bool: def check(l, r): stackL = list() stackR = list() stackL.append(l) stackR.append(r) while stackL: left = stackL.pop(0) right = stackR.pop(0) if not left and not right: continue if (not left or not right) or (left.val != right.val): return False stackL.append(left.left) stackL.append(left.right) stackR.append(right.right) stackR.append(right.left) return True return check(root, root)
进阶:
你可以运用递归和迭代两种方法解决这个问题吗?