-
Notifications
You must be signed in to change notification settings - Fork 0
/
814_Binary Tree Pruning.js
43 lines (38 loc) · 1018 Bytes
/
814_Binary Tree Pruning.js
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
// https://leetcode.com/problems/binary-tree-pruning/description/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
function TreeNode(val) {
this.val = val;
this.left = this.right = null;
}
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var pruneTree = function (root) {
if (!root) return root;
root.left = pruneTree(root.left);
root.right = pruneTree(root.right);
if (!root.left && !root.right && root.val === 0) {
root = null;
}
return root;
};
var root = new TreeNode(1);
root.right = new TreeNode(0);
root.right.left = new TreeNode(0);
root.right.right = new TreeNode(1);
console.log(JSON.stringify(pruneTree(root)));
var root = new TreeNode(1);
root.right = new TreeNode(1);
root.right.left = new TreeNode(0);
root.right.right = new TreeNode(1);
root.left = new TreeNode(0);
root.left.left = new TreeNode(0);
root.left.right = new TreeNode(0);
console.log(JSON.stringify(pruneTree(root)));