Leetcode 173. Binary Search Tree Iterator

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Binary Search Tree Iterator

2. Solution

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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
private:
stack<TreeNode*> index;
public:
BSTIterator(TreeNode *root) {
traverseLeft(root);
}

/** @return whether we have a next smallest number */
bool hasNext() {
return !index.empty();
}

/** @return the next smallest number */
int next() {
TreeNode* current = index.top();
index.pop();
traverseLeft(current->right);
return current->val;
}

void traverseLeft(TreeNode* root) {
TreeNode* current = root;
while(current) {
index.push(current);
current = current->left;
}
}
};

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

Reference

  1. https://leetcode.com/problems/binary-search-tree-iterator/description/
如果有收获,可以请我喝杯咖啡!