File tree 1 file changed +40
-0
lines changed
1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Recursion
3
+ * h = height of the tree;
4
+ * Time O(h) | Space O(h)
5
+ * Definition for a binary tree node.
6
+ * function TreeNode(val, left, right) {
7
+ * this.val = (val===undefined ? 0 : val)
8
+ * this.left = (left===undefined ? null : left)
9
+ * this.right = (right===undefined ? null : right)
10
+ * }
11
+ */
12
+ /**
13
+ * @param {TreeNode } root
14
+ * @param {number } key
15
+ * @return {TreeNode }
16
+ */
17
+ var deleteNode = function ( root , key ) {
18
+ if ( ! root ) return root ;
19
+
20
+ if ( key === root . val ) {
21
+ if ( ! root . left ) return root . right ;
22
+ if ( ! root . right ) return root . left ;
23
+
24
+ // find the smallest val in right bst
25
+ let curr = root . right ;
26
+ while ( curr . left ) {
27
+ curr = curr . left ;
28
+ }
29
+ // change the curr value
30
+ root . val = curr . val ;
31
+
32
+ root . right = deleteNode ( root . right , root . val ) ;
33
+ } else if ( key < root . val ) {
34
+ root . left = deleteNode ( root . left , key ) ;
35
+ } else {
36
+ root . right = deleteNode ( root . right , key ) ;
37
+ }
38
+
39
+ return root ;
40
+ } ;
You can’t perform that action at this time.
0 commit comments