1+ // question link : https://leetcode.com/problems/delete-node-in-a-bst/description/
2+ class Solution {
3+
4+ //1.reach the given node using recursion,if not found just return
5+ public TreeNode deleteNode (TreeNode root , int val ) {
6+ if (root ==null )
7+ return root ;
8+
9+
10+ if (val ==root .val )
11+ {//2. After found, there are 4 conditions
12+
13+ //2.1 cur node have both left & ryt nodes.
14+ if (root .left !=null && root .right !=null )
15+ {
16+
17+ /*concept : take ryt node's left subtree,
18+ connect it to left node's ryt most node
19+ connect the updated left node to ryt node's left (i.e.. ryt.left=left)
20+ and return the updated ryt node. (deleting the cur node)
21+ */
22+
23+ TreeNode ryt =cleft (root .left ,root .right );
24+ return ryt ;
25+ }
26+
27+ //2.2 have only ryt node
28+ else if (root .left ==null && root .right !=null )
29+ {
30+ return root .right ;
31+ }
32+
33+ //2.3 have only left node
34+ else if (root .left !=null && root .right ==null )
35+ {
36+ return root .left ;
37+ }
38+
39+ //2.4 have no child nodes.
40+ else
41+ {
42+ return null ;
43+ }
44+ }
45+
46+ if (val <root .val )
47+ {
48+ root .left =deleteNode (root .left ,val );
49+ return root ;
50+ }
51+ else
52+ {
53+ root .right =deleteNode (root .right ,val );
54+ return root ;
55+ }
56+ }
57+
58+ //cleft() -> does insert() func and connect the updated left to (ryt.left)
59+ TreeNode cleft (TreeNode left ,TreeNode ryt )
60+ {
61+ if (ryt .left ==null )
62+ {
63+ ryt .left =left ;
64+ return ryt ;
65+ }
66+ TreeNode temp =ryt .left ;
67+ ryt .left =insert (left ,temp );
68+ return ryt ;
69+
70+ }
71+
72+ //insert() -> connect ryt node's left subtree(temp) to rytmost of left node and return the updated left node
73+ TreeNode insert (TreeNode root ,TreeNode temp )
74+ {
75+ if (root ==null )
76+ return temp ;
77+
78+ root .right =insert (root .right ,temp );
79+
80+ return root ;
81+ }
82+
83+
84+
85+ }
0 commit comments