forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDelete Node in a BST.js
38 lines (33 loc) · 925 Bytes
/
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
/**
* 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)
* }
*/
const getLeftMostNode=(root)=>{
if(!root)return null;
let node=getLeftMostNode(root.left);
return node?node:root;
}
/**
* @param {TreeNode} root
* @param {number} key
* @return {TreeNode}
*/
var deleteNode = function(root, key) {
if(!root)return null;
if(root.val>key){
root.left=deleteNode(root.left,key);
}else if(root.val<key){
root.right= deleteNode(root.right,key);
}else{
if(!root.left)return root.right;
if(!root.right)return root.left;
let succ_node=getLeftMostNode(root.right);
root.val=succ_node.val;
root.right= deleteNode(root.right,succ_node.val);
}
return root;
};