-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathKth-smallest-element-in-BST.cpp
36 lines (36 loc) · 1.08 KB
/
Kth-smallest-element-in-BST.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
// Name: Hussain Iftikhar
// Username: hussainiftikhar5242
// Approach: First store all node in vector and then sort the vector, after sorting the vector return the kth-1 index
/**
* Definition for a binary tree node.
* 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) {}
* };
*/
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
vector<int> temp;
TreeNode* node;
stack<TreeNode *> s1;
s1.push(root);
while(!s1.empty())
{
TreeNode * curr = s1.top();
int val=curr->val;
temp.push_back(val);
s1.pop();
if(curr->left != NULL)
s1.push(curr->left);
if(curr->right != NULL)
s1.push(curr->right);
}
sort(temp.begin(),temp.end());
return temp.at(k-1);
}
};