101. Symmetric Tree
Easy
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3]
is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3]
is not:
1
/ \
2 2
\ \
3 3
Follow up: Solve it both recursively and iteratively.
笔记:
判断是不是平衡二叉树,假设有两个节点n1,n2,如果n1的左子节点等于n2的右子节点,n1的右子节点等于n2的左子节点,那么n1,n2平衡。一直递归下去,比较完所有的节点。
方法1:递归
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if root is None:
return True
def _sym(left_node: TreeNode, right_node: TreeNode) -> bool:
if left_node is None and right_node is None:
return True
if left_node is None or right_node is None or left_node.val != right_node.val:
return False
return _sym(left_node.left, right_node.right) and _sym(left_node.right, right_node.left)
return _sym(root.left, root.right)
方法2:迭代
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if root is None:
return True
s1, s2 = [root.left], [root.right]
while s1 and s2:
s1_node, s2_node = s1.pop(), s2.pop()
if s1_node is None and s2_node is None:
continue
if (s1_node is None and s2_node) or (s1_node and s2_node is None) or s1_node.val != s2_node.val:
return False
s1.append(s1_node.left)
s2.append(s2_node.right)
s1.append(s1_node.right)
s2.append(s2_node.left)
return True