Skip to content

Commit 04f6ff9

Browse files
Create Day 20 Kth Smallest Element in a BST.cpp
1 parent 707fd5a commit 04f6ff9

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed
+75
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
PROBLEM:
2+
3+
4+
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
5+
6+
Note:
7+
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
8+
9+
Example 1:
10+
Input: root = [3,1,4,null,2], k = 1
11+
3
12+
/ \
13+
1 4
14+
\
15+
2
16+
Output: 1
17+
18+
Example 2:
19+
Input: root = [5,3,6,2,4,null,null,1], k = 3
20+
5
21+
/ \
22+
3 6
23+
/ \
24+
2 4
25+
/
26+
1
27+
Output: 3
28+
Follow up:
29+
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently?
30+
How would you optimize the kthSmallest routine?
31+
32+
33+
34+
35+
SOLUTION:
36+
37+
38+
/**
39+
* Definition for a binary tree node.
40+
* struct TreeNode {
41+
* int val;
42+
* TreeNode *left;
43+
* TreeNode *right;
44+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
45+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
46+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
47+
* };
48+
*/
49+
class Solution {
50+
public:
51+
52+
void helper(TreeNode* root,int& k,int& ans)
53+
{
54+
if(root==NULL || k==0)
55+
return;
56+
57+
helper(root->left,k,ans);
58+
k--;
59+
if(k==0)
60+
{
61+
ans=root->val;
62+
}
63+
helper(root->right,k,ans);
64+
}
65+
66+
int kthSmallest(TreeNode* root, int k) {
67+
68+
int ans;
69+
helper(root,k,ans);
70+
71+
72+
return ans;
73+
74+
}
75+
};

0 commit comments

Comments
 (0)