forked from JoshCrozier/leetcode-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0814-binary-tree-pruning.js
More file actions
32 lines (31 loc) · 864 Bytes
/
0814-binary-tree-pruning.js
File metadata and controls
32 lines (31 loc) · 864 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
/**
* 814. Binary Tree Pruning
* https://leetcode.com/problems/binary-tree-pruning/
* Difficulty: Medium
*
* 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.
*/
/**
* 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;
root.left = pruneTree(root.left);
root.right = pruneTree(root.right);
if (!root.left && !root.right && root.val === 0) {
return null;
}
return root;
};