Skip to content

Commit 9f1d69d

Browse files
authored
Clean up code
1 parent bbd39e7 commit 9f1d69d

File tree

1 file changed

+29
-23
lines changed

1 file changed

+29
-23
lines changed

tree/Yu/101_symmetricTree.py

+29-23
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,35 @@
1-
#!/usr/bin/python
2-
# -*- coding: utf-8 -*-
3-
4-
# Author: Yu Zhou
5-
# ****************
6-
# Descrption:
7-
# 101. Symmetric Tree
8-
# Given a binary tree, check whether it is a mirror of itself
9-
# (ie, symmetric around its center).
10-
# ****************
11-
12-
# 思路:
13-
# 这道题只要知道一个规律,就是左边Child要等于右边Child,就很容易了
14-
# 先解决Root的Edge,之后在对其他进行一个统一处理,我选择写一个Helper,也可以不写
15-
16-
# if not left or not right: return left == right的意思是:
17-
# if not left or not right: return False
18-
# if not left and not right: return True
19-
201
class Solution(object):
2+
# Queue
213
def isSymmetric(self, root):
4+
if not root:
5+
return True
6+
queue = [(root.left, root.right)]
7+
while queue:
8+
left, right = queue.pop(0)
9+
10+
if not left and not right:
11+
continue
12+
if not left or not right:
13+
return False
14+
if left.val != right.val:
15+
return False
16+
queue.append((left.left, right.right))
17+
queue.append((left.right,right.left))
18+
return True
19+
20+
21+
# Recursion
22+
def isSymmetric2(self, root):
23+
if not root:
24+
return True
2225

23-
if not root: return True
2426
def dfs(left, right):
25-
if not left or not right: return left == right
26-
if left.val != right.val: return False
27-
return dfs(left.left, right.right) and dfs(left.right, right.left)
27+
if not left and not right:
28+
return True
29+
if not left or not right:
30+
return False
31+
if left.val != right.val:
32+
return False
33+
return dfs(left.left , right.right) and dfs(left.right, right.left)
2834

2935
return dfs(root.left, root.right)

0 commit comments

Comments
 (0)