-
Notifications
You must be signed in to change notification settings - Fork 118
/
KthSmallestElementInBST.cpp
51 lines (40 loc) · 1.19 KB
/
KthSmallestElementInBST.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <bits/stdc++.h>
using namespace std;
// Problem Link : https://leetcode.com/problems/kth-smallest-element-in-a-bst/
/*
Problem Statement :
Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
/*
Approach :
We pass k by reference
Do inorder traversal of tree
if k is 0 at any time this means we have already reached kth smallest node : we simply return answer from here
else we recur for left and right half after decrementing k
*/
void inorder(TreeNode*&T,int &k,int& ans){
if (T==nullptr)
return;
inorder(T->left,k,ans);
--k;
if (k==0) ans=T->val;
inorder(T->right,k,ans);
}
int kthSmallest(TreeNode* root, int k) {
int ans;
inorder(root,k,ans);
return ans;
}
int main(){
TreeNode* T = new TreeNode();
//buildtree...
cout<<kthSmallest(T,1)<<'\n';
}