Skip to content

Commit b6f3b5e

Browse files
committed
DeleteNodeinaBST
1 parent 7dcde1b commit b6f3b5e

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public TreeNode deleteNode(TreeNode root, int key) {
3+
if(root == null) return root;
4+
if(root.val == key){
5+
if(root.left == null) return root.right;
6+
if(root.right == null) return root.left;
7+
TreeNode succ = findSucessor(root);
8+
root.val = succ.val;
9+
root.right = deleteNode(root.right, succ.val);
10+
return root;
11+
}
12+
else if(root.val < key){
13+
root.right = deleteNode(root.right, key);
14+
}
15+
else{
16+
root.left = deleteNode(root.left, key);
17+
}
18+
return root;
19+
20+
}
21+
22+
private TreeNode findSucessor(TreeNode node){
23+
TreeNode cur = node.right;
24+
while(cur != null && cur.left != null){
25+
cur = cur.left;
26+
}
27+
return cur;
28+
}
29+
30+
}

0 commit comments

Comments
 (0)