题目描述:

Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.

Calling next() will return the next smallest number in the BST.

**Note: **next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.

二叉树的非递归中序遍历, 只不过不是放在循环中, 而是通过next来触发每一步的进行.

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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
TreeNode *BST, *curNode;
vector<TreeNode*> path;
public:
BSTIterator(TreeNode *root) {
BST = root;
mostLeft(root);
curNode = nullptr;
}

TreeNode* mostLeft(TreeNode *root){
TreeNode *node = root;
while(node) {
path.push_back(node);
node = node->left;
}
return node;
}

/** @return whether we have a next smallest number */
bool hasNext() {
if(path.empty() && !curNode) return false;
else return true;
}

/** @return the next smallest number */
int next() {
//curNode = path.back();
int ans;
if(!curNode){
ans = path.back()->val;
curNode = path.back()->right;
path.pop_back();
}
else{
mostLeft(curNode);
ans = path.back()->val;
curNode = path.back()->right;
path.pop_back();
}
//cout<<ans<<endl;
return ans;
}
};

/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/