Delete Node in a BST 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
const getLeftMostNode = (root) => {
11
if (!root) return null;
12
let node = getLeftMostNode(root.left);
13
return node ? node : root;
14
};
15
/**
16
* @param {TreeNode} root
17
* @param {number} key
18
* @return {TreeNode}
19
*/
20

21
var deleteNode = function (root, key) {
22
if (!root) return null;
23
if (root.val > key) {
24
root.left = deleteNode(root.left, key);
25
} else if (root.val < key) {
26
root.right = deleteNode(root.right, key);
27
} else {
28
if (!root.left) return root.right;
29
if (!root.right) return root.left;
30
let succ_node = getLeftMostNode(root.right);
31
root.val = succ_node.val;
32
root.right = deleteNode(root.right, succ_node.val);
33
}
34
return root;
35
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0