给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [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
递归:
- 首先以根节点以及其左右子树,左子树的左子树和右子树的右子树相同,左子树的右子树和右子树的左子树相同,两个条件都要符合
- 所以我们第一个传根节点的左子树和右子树,先判断左右子树根结点的比较。然后分辨对左子树的左子树和右子树的右子树。左子树的右子树和右子树的左子树进行判断。只有两个条件都满足则返回的是true
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
def helper(left, right):
if not left and not right:
return True
if not left or not right:
return False
if left.val == right.val:
return helper(left.left, right.right) and helper(left.right, right.left)
return helper(root.left, root.right) if root else True
O(n)
迭代
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
return True
stack = [root.left, root.right]
while stack:
right = stack.pop()
left = stack.pop()
if not left and not right:
continue
if not left or not right:
return False
if right.val != left.val:
return False
stack.extend([left.left, right.right, left.right, right.left])
return True
O(n)