Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitca2c275

Browse files
Update 0450-delete-node-in-a-bst.java
The earlier code provided wasn't working for all cases. I have edited the code.
1 parent40e983b commitca2c275

File tree

1 file changed

+14
-22
lines changed

1 file changed

+14
-22
lines changed

‎java/0450-delete-node-in-a-bst.java‎

Lines changed: 14 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,24 @@
1-
/**
2-
* TC : log (n)
3-
*
4-
* */
51
classSolution {
6-
publicTreeNodeminimumVal(TreeNoderoot) {
7-
TreeNodecurr =root;
8-
while (curr !=null &&curr.left !=null) {
9-
curr =curr.left;
2+
publicTreeNodefindMin(TreeNodenode) {
3+
TreeNodecurrent =node;
4+
while (current.left !=null) {
5+
current =current.left;
106
}
11-
returncurr;
7+
returncurrent;
128
}
139

1410
publicTreeNodedeleteNode(TreeNoderoot,intkey) {
1511
if (root ==null)returnnull;
1612

17-
if (key >root.val) {
18-
root.right =deleteNode(root.right,key);
19-
}elseif (key <root.val) {
20-
root.left =deleteNode(root.left,key);
21-
}else {
22-
if (root.left ==null) {
23-
returnroot.right;
24-
}elseif (root.right ==null) {
25-
returnroot.left;
26-
}else {
27-
TreeNodeminVal =minimumVal(root);
28-
root.val =minVal.val;
29-
root.right =deleteNode(root.right,minVal.val);
13+
if (root.val >key)root.left =deleteNode(root.left,key);
14+
elseif (root.val <key)root.right =deleteNode(root.right,key);
15+
else {
16+
if (root.left ==null)returnroot.right;
17+
elseif (root.right ==null)returnroot.left;
18+
else {
19+
TreeNodesuccessor =findMin(root.right);
20+
root.val =successor.val;
21+
root.right =deleteNode(root.right,successor.val);
3022
}
3123
}
3224
returnroot;

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp