File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
18 - Binary Search Tree Data Structure Problems/07 - K-th Smallest Element in BST Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ // Return the Kth smallest element in the given BST
4+ int KthSmallestElement (Node *root, int k) {
5+ Node* current = root;
6+ int count = 0 ;
7+ int element = -1 ;
8+
9+ while (current != NULL ){
10+ if (current -> left == NULL ){
11+ count++;
12+ if (count == k) element = current -> data;
13+ current = current -> right;
14+ }else {
15+ Node* predecessor = current -> left;
16+ while (predecessor -> right != NULL && predecessor -> right != current){
17+ predecessor = predecessor -> right;
18+ }
19+
20+ if (predecessor -> right == NULL ){
21+ predecessor -> right = current;
22+ current = current -> left;
23+ }else {
24+ predecessor -> right = NULL ;
25+ count++;
26+ if (count == k) element = current -> data;
27+ current = current -> right;
28+ }
29+ }
30+ if (element != -1 ) break ;
31+ }
32+
33+
34+ return element;
35+ }
36+ };
You can’t perform that action at this time.
0 commit comments