-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary_search_tree_iterator.cpp
72 lines (63 loc) · 1.48 KB
/
binary_search_tree_iterator.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// =====================================================================================
//
// Filename: binary_search_tree_iterator.cpp
//
// Description: 173. Binary Search Tree Iterator.
//
// Version: 1.0
// Created: 09/12/2019 06:12:59 PM
// Revision: none
// Compiler: g++
//
// Author: Zhu Xianfeng (), [email protected]
// Organization:
//
// =====================================================================================
#include <stdio.h>
#include <stack>
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
// Non-recursive traversal
class BSTIterator
{
public:
BSTIterator(TreeNode* root)
{
ptr_ = root;
}
// @return the next smallest number
int next()
{
while (ptr_ != nullptr)
{
nodes_.push(ptr_);
ptr_ = ptr_->left;
}
int val = 0;
ptr_ = nodes_.top();
val = ptr_->val;
ptr_ = ptr_->right;
nodes_.pop();
return val;
}
// @return whether we have a next smallest number
bool hasNext()
{
return (ptr_ != nullptr || !nodes_.empty());
}
private:
TreeNode* ptr_ = nullptr;
std::stack<TreeNode*> nodes_;
};
int main(int argc, char* argv[])
{
TreeNode* root = nullptr;
BSTIterator iterator(root);
printf("Has next? %s\n", (iterator.hasNext() ? "Yes" : "No"));
return 0;
}