-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary-tree-pruning
66 lines (58 loc) · 1.87 KB
/
binary-tree-pruning
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
/*
Binary Tree Pruning
Given the root of a binary tree, return the same tree where every subtree (of the given tree)
not containing a 1 has been removed.
A subtree of a node node is node plus every node that is a descendant of node.
Example 1:
1 1
\ => \
0 0
/ \ \
0 1 1
Input: root = [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.
Example 2:
1 1
/ \ \
0 1 => 1
/ \ / \ \
0 0 0 1 1
Input: root = [1,0,1,0,0,0,1]
Output: [1,null,1,null,1]
Example 3:
Input: root = [1,1,0,1,1,0,1,0]
Output: [1,1,0,1,1,null,1]
Constraints:
The number of nodes in the tree is in the range [1, 200].
Node.val is either 0 or 1.
*/
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var pruneTree = function(root) {
if(!root) return null;
dfs(root)
if(root.val === 1 || root.left || root.right)
return root
return null;
function dfs(node){
if(!node) return 0;
let leftSum = dfs(node.left);
let rightSum = dfs(node.right);
if(!leftSum) node.left = null;
if(!rightSum) node.right = null;
return node.val + leftSum + rightSum;
}
};