-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlintcode86Binary Search Tree Iterator.cpp
More file actions
70 lines (65 loc) · 1.27 KB
/
Copy pathlintcode86Binary Search Tree Iterator.cpp
File metadata and controls
70 lines (65 loc) · 1.27 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
#include<iostream>
#include<vector>
#include<stack>
using namespace std;
class TreeNode {
public:
int val;
TreeNode *left, *right;
TreeNode(int val) {
this->val = val;
this->left = this->right = NULL;
}
};
class BSTIterator {
private:
stack<TreeNode *> stk;
public:
/*
* @param root: The root of binary tree.
*/BSTIterator(TreeNode * root) {
// do intialization if necessary
while(root != NULL)
{
stk.push(root);
root = root->left;
}
}
/*
* @return: True if there has next node, or false
*/
bool hasNext() {
// write your code here
return !stk.empty();
}
/*
* @return: return next node
*/
TreeNode *next() {
// write your code here
TreeNode *nextNode = stk.top(); stk.pop();
if(nextNode->right != NULL)
{
TreeNode *curr = nextNode->right;
while(curr != NULL)
{
stk.push(curr);
curr = curr->left;
}
}
return nextNode;
}
};
int main()
{
TreeNode T0(4), T1(3), T2(2), T3(1), T4(0);
T0.left = &T1;
T1.left = &T2;
T2.left = &T3;
T3.left = &T4;
BSTIterator BST(&T0);
auto out = BST.next();
auto out1 = out->next();
cout<<out1->val<<endl;
return 0;
}