forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeleteNodeInBST.java
More file actions
29 lines (25 loc) · 769 Bytes
/
DeleteNodeInBST.java
File metadata and controls
29 lines (25 loc) · 769 Bytes
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
public class DeleteNodeInBST {
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) {
return null;
}
if (key < root.val) {
root.left = deleteNode(root.left, key);
} else if (key > root.val) {
root.right = deleteNode(root.right, key);
} else {
if (root.left == null) {
return root.right;
} else if (root.right == null) {
return root.left;
}
TreeNode node = root.right;
while (node.left != null) {
node = node.left;
}
root.val = node.val;
root.right = deleteNode(root.right, node.val);
}
return root;
}
}