-
Notifications
You must be signed in to change notification settings - Fork 0
/
146.py
75 lines (57 loc) · 1.41 KB
/
146.py
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
"""
Problem:
Given a binary tree where all nodes are either 0 or 1, prune the tree so that subtrees
containing all 0s are removed.
For example, given the following tree:
0
/ \
1 0
/ \
1 0
/ \
0 0
should be pruned to:
0
/ \
1 0
/
1
We do not remove the tree at the root or its left child because it still has a 1 as a
descendant.
"""
from DataStructures.Tree import Node, BinaryTree
def prune_helper(node: Node) -> None:
if node.left:
prune_helper(node.left)
if node.left.val == 0:
if not node.left.left and not node.left.right:
temp = node.left
node.left = None
del temp
if node.right:
prune_helper(node.right)
if node.right.val == 0:
if not node.right.left and not node.right.right:
temp = node.right
node.right = None
del temp
def prune(tree: BinaryTree) -> BinaryTree:
if tree.root:
prune_helper(tree.root)
return tree
if __name__ == "__main__":
tree = BinaryTree()
tree.root = Node(0)
tree.root.left = Node(1)
tree.root.right = Node(0)
tree.root.right.left = Node(1)
tree.root.right.right = Node(0)
tree.root.right.left.left = Node(0)
tree.root.right.left.right = Node(0)
print(tree)
print(prune(tree))
"""
SPECS:
TIME COMPLEXITY: O(n)
SPACE COMPLEXITY: O(log(n))
"""