0%

Leetcode 101 对称二叉树

给你一个二叉树的根节点 root , 检查它是否 轴对称

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Definition for a binary tree node.
# 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: Optional[TreeNode]) -> bool:
def helper(left_tree, right_tree):
if not left_tree and not right_tree: return True
if left_tree and right_tree:
if left_tree.val == right_tree.val and helper(left_tree.right, right_tree.left) and helper(left_tree.left, right_tree.right):
return True
return False
return helper(root.left, root.right)

# 迭代
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
queue = [root, root]
while queue:
cur_left, cur_right = queue[0], queue[1]
if not cur_left and not cur_right:
queue = queue[2:]
continue
if not cur_left or not cur_right or cur_left.val != cur_right.val:
return False
queue.append(cur_left.left)
queue.append(cur_right.right)
queue.append(cur_left.right)
queue.append(cur_right.left)
queue = queue[2:]
return True