-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0814-binary-tree-pruning.py
More file actions
32 lines (24 loc) · 876 Bytes
/
0814-binary-tree-pruning.py
File metadata and controls
32 lines (24 loc) · 876 Bytes
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
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
def containOne(node):
if not node:
return False
leftContainOne = containOne(node.left)
rightContainOne = containOne(node.right)
if not leftContainOne:
node.left = None
if not rightContainOne:
node.right = None
return node.val or containOne(node.left) or containOne(node.right)
return root if containOne(root) else None
root = TreeNode(1)
root.right = TreeNode(0)
root.right.left = TreeNode(0)
root.right.right = TreeNode(1)
print(Solution().pruneTree(root))