-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathsymmetric_tree.py
More file actions
38 lines (31 loc) · 1.16 KB
/
symmetric_tree.py
File metadata and controls
38 lines (31 loc) · 1.16 KB
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
36
37
38
# 对称二叉树
# https://leetcode-cn.com/problems/symmetric-tree/
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 递归的方式,深度优先
def isSymmetric_1(self, root: TreeNode) -> bool:
def helper(a, b) -> bool:
if not a and not b:
return True
if not a or not b or a.val != b.val:
return False
return helper(a.left, b.right) and helper(a.right, b.left)
return helper(root, root)
# 使用一个队列,广度优先
def isSymmetric_2(self, root: TreeNode) -> bool:
def helper(node1: TreeNode, node2: TreeNode) -> bool:
queue = [node1, node2]
while len(queue) > 0:
n1, n2 = queue.pop(0), queue.pop(0)
if not n1 and not n2:
continue
if not n1 or not n2 or n1.val != n2.val:
return False
queue.append(n1.left), queue.append(n2.right)
queue.append(n1.right), queue.append(n2.left)
return True
return helper(root, root)