-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy path0450-delete-node-in-a-bst.js
48 lines (47 loc) · 1.24 KB
/
0450-delete-node-in-a-bst.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
44
45
46
47
48
/**
* 450. Delete Node in a BST
* https://leetcode.com/problems/delete-node-in-a-bst/
* Difficulty: Medium
*
* Given a root node reference of a BST and a key, delete the node with the given key in
* the BST. Return the root node reference (possibly updated) of the BST.
*
* Basically, the deletion can be divided into two stages:
* 1. Search for a node to remove.
* 2. If the node is found, delete the 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
* @param {number} key
* @return {TreeNode}
*/
var deleteNode = function(root, key) {
if (!root) return root;
if (root.val < key) {
root.right = deleteNode(root.right, key);
} else if (root.val > key) {
root.left = deleteNode(root.left, key);
} else {
if (root.left === null) {
return root.right;
} else if (root.right === null) {
return root.left;
} else {
let node = root.right;
while (node.left) {
node = node.left;
}
node.left = root.left;
return root.right;
}
}
return root;
};