Skip to content

Commit fedebd4

Browse files
authored
Create Solution.java
1 parent c1d24e2 commit fedebd4

File tree

1 file changed

+29
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)