-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path230.cpp
More file actions
91 lines (74 loc) · 1.74 KB
/
230.cpp
File metadata and controls
91 lines (74 loc) · 1.74 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*
* Written by Nitin Kumar Maharana
* nitin.maharana@gmail.com
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//Iterative Solution.
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
stack<TreeNode*> memory;
memory.push(root);
while(root || !memory.empty())
{
if(root)
{
memory.push(root);
root = root->left;
}
else
{
root = memory.top();
memory.pop();
k--;
if(!k)
return root->val;
root = root->right;
}
}
}
};
//Recursive Solution.
class Solution {
public:
int kthSmallest(TreeNode* root, int &k) {
if(!root)
return 0;
int result;
result = kthSmallest(root->left, k);
if(!k)
return result;
k--;
if(!k)
return root->val;
return kthSmallest(root->right, k);
}
};
//One more Recursive Solution.
class Solution {
TreeNode *result;
int kthSmallestUtil(TreeNode *root, int k)
{
if(!root)
return 0;
int l, r;
l = kthSmallestUtil(root->left, k);
if(l+1 == k)
result = root;
r = kthSmallestUtil(root->right, k-l-1);
return l+r+1;
}
public:
int kthSmallest(TreeNode* root, int k) {
kthSmallestUtil(root, k);
return result->val;
}
};