Binary Tree Pruning LeetCode solution in JavaScript

1
/**
2
* Definition for a binary tree node.
3
* function TreeNode(val, left, right) {
4
* this.val = (val===undefined ? 0 : val)
5
* this.left = (left===undefined ? null : left)
6
* this.right = (right===undefined ? null : right)
7
* }
8
*/
9
/**
10
* @param {TreeNode} root
11
* @return {TreeNode}
12
*/
13
var pruneTree = function (root) {
14
let rec = function (node) {
15
if (node == null) return null;
16
if (node.val === 0 && node.left == null && node.right == null) {
17
return null;
18
}
19
node.left = rec(node.left);
20
node.right = rec(node.right);
21
// For updated tree structure if threre are leaf nodes with zero value present, if yes then return null otherewise return node itself.
22
if (node.val === 0 && node.left == null && node.right == null) {
23
return null;
24
}
25
return node;
26
};
27
rec(root);
28
if (root.val == 0 && root.left == null && root.right == null) return null;
29

30
return root;
31
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0