File tree Expand file tree Collapse file tree 1 file changed +14
-22
lines changed Expand file tree Collapse file tree 1 file changed +14
-22
lines changed Original file line number Diff line number Diff line change 1- /**
2- * TC : log (n)
3- *
4- * */
51class Solution {
6- public TreeNode minimumVal (TreeNode root ) {
7- TreeNode curr = root ;
8- while (curr != null && curr .left != null ) {
9- curr = curr .left ;
2+ public TreeNode findMin (TreeNode node ) {
3+ TreeNode current = node ;
4+ while (current .left != null ) {
5+ current = current .left ;
106 }
11- return curr ;
7+ return current ;
128 }
139
1410 public TreeNode deleteNode (TreeNode root , int key ) {
1511 if (root == null ) return null ;
1612
17- if (key > root .val ) {
18- root .right = deleteNode (root .right , key );
19- } else if (key < root .val ) {
20- root .left = deleteNode (root .left , key );
21- } else {
22- if (root .left == null ) {
23- return root .right ;
24- } else if (root .right == null ) {
25- return root .left ;
26- } else {
27- TreeNode minVal = 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+ else if (root .val < key ) root .right = deleteNode (root .right , key );
15+ else {
16+ if (root .left == null ) return root .right ;
17+ else if (root .right == null ) return root .left ;
18+ else {
19+ TreeNode successor = findMin (root .right );
20+ root .val = successor .val ;
21+ root .right = deleteNode (root .right , successor .val );
3022 }
3123 }
3224 return root ;
You can’t perform that action at this time.
0 commit comments