File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed
solution/0450.Delete Node in a BST Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments