Skip to content

Commit e6e3547

Browse files
author
Chris Wu
committed
no message
1 parent b214d55 commit e6e3547

File tree

2 files changed

+33
-6
lines changed

2 files changed

+33
-6
lines changed

problems/binary-tree-pruning.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution(object):
2+
def pruneTree(self, root):
3+
def hasOne(node):
4+
if not node: return False
5+
6+
left_has_one = hasOne(node.left)
7+
right_has_one = hasOne(node.right)
8+
9+
if not left_has_one: node.left = None
10+
if not right_has_one: node.right = None
11+
12+
return node.val==1 or left_has_one or right_has_one
13+
14+
return root if hasOne(root) else None
15+
16+
class Solution(object):
17+
def pruneTree(self, node):
18+
if not node: return None
19+
node.left = self.pruneTree(node.left)
20+
node.right = self.pruneTree(node.right)
21+
if not node.left and not node.right and node.val==0: return None
22+
return node
23+
24+
"""
25+
Time complexity is O(N). Because we traverse all the nodes.
26+
Space complexity is O(LogN). The tree's height is about O(LogN), so we have O(LogN) level of recursion and used up O(LogN) of stack memory
27+
"""
Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,28 @@
11
"""
22
The description wants us to report from left to right, top to bottom.
33
Thus, we keep add value into `temp` with `x_position` as the key and `(y_position, node.val)` as the value.
4-
And maintain `min_index`, `max_index` at the same time. So we know how to iterate the `temp`.
4+
And maintain `min_x`, `max_x` at the same time. So we know how to iterate the `temp`.
55
"""
66
from collections import defaultdict
77

88
class Solution(object):
99
def verticalTraversal(self, root):
1010
temp = defaultdict(list)
11-
min_index = 0
12-
max_index = 0
11+
min_x = 0
12+
max_x = 0
1313

1414
stack = []
1515
stack.append((root, 0, 0))
1616
while stack:
1717
node, x, y = stack.pop()
1818
temp[x].append((y, node.val)) #append the value of height, so we can sort by height later on
19-
min_index = min(min_index, x)
20-
max_index = max(max_index, x)
19+
min_x = min(min_x, x)
20+
max_x = max(max_x, x)
2121
if node.left: stack.append((node.left, x-1, y+1))
2222
if node.right: stack.append((node.right, x+1, y+1))
2323

2424
opt = []
25-
for i in range(min_index, max_index+1):
25+
for i in range(min_x, max_x+1):
2626
opt.append([v for y, v in sorted(temp[i])]) #the temp[i] will be sorted by y_position then sorted by node.val
2727

2828
return opt

0 commit comments

Comments
 (0)