-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKth_Smallest_in_BST.cpp
More file actions
52 lines (44 loc) · 946 Bytes
/
Kth_Smallest_in_BST.cpp
File metadata and controls
52 lines (44 loc) · 946 Bytes
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
52
#include "stdafx.h"
#include "iostream"
#include "vector"
#include "string"
#include "map"
#include <algorithm>
#include <stdlib.h>
#include <time.h>
#include <stack>
using namespace std;
struct Node{
int val;
Node *left;
Node *right;
Node(int _v):val(_v),left(NULL),right(NULL){}
};
void kthSmallestHelper(Node* root, int k, int &i, int &result)
{
if(!root)return;
kthSmallestHelper(root->left, k, i, result);
i++;
if(i==k){result=root->val;return;}
if(i<k)kthSmallestHelper(root->right, k, i, result);
}
int kthSmallest(Node* root, int k)
{
int result, i=0;
kthSmallestHelper(root, k, i ,result);
return result;
}
int _tmain(int argc, _TCHAR* argv[])
{
Node *t1=new Node(1);
Node *t2=new Node(2);
Node* t3=new Node(3);
Node* t4=new Node(4);
Node* t5=new Node(5);
t3->left=t2;
t3->right=t4;
t2->left=t1;
t4->right=t5;
cout<<kthSmallest(t3, 5)<<endl;
return 0;
}