LeetCode #814 Binary Tree Pruning

Problem

We are given the head node root of a binary tree, where additionally every node’s value is either a 0 or a 1.

Return the same tree where every subtree (of the given tree) not containing a 1 has been removed.

(Recall that the subtree of a node X is X, plus every node that is a descendant of X.)

Examples

1
2
3
4
5
6
Input: [1,null,0,0,1]
Output: [1,null,0,null,1]

Explanation:
Only the red nodes satisfy the property "every subtree not containing a 1".
The diagram on the right represents the answer.

img

1
2
Input: [1,0,1,0,0,0,1]
Output: [1,null,1,null,1]

img

1
2
Input: [1,1,0,1,1,0,1,0]
Output: [1,1,0,1,1,null,1]

img

Solution

Method: Depth-first Search

Time Complexity: O(n)

Space Complexity:

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
class Solution:
def pruneTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
stack = [(root, False)]

while stack:
node, visited = stack.pop()
if node:
if not visited:
stack.append((node, True))
stack.append((node.right, False))
stack.append((node.left, False))
else:
if node.left and node.left.val == -1:
node.left = None
if node.right and node.right.val == -1:
node.right = None
if not node.left and not node.right:
if node.val == 0:
node.val = -1

return root