LeetCode 173
Binary Search Tree Iterator
Problem Description:
这道题目考察的就是构造二叉搜索树:左节点<根节点<右节点,先把最左边的节点push进栈,然后检查每个节点是否有右节点,有的话将右节点作为新的根节点,重复上述操作。
具体的题目信息:
https://leetcode.com/problems/binary-search-tree-iterator/description/- Solution:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
public:
BSTIterator(TreeNode *root) {
while(root) {
node.push(root);
root = root->left;
}
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !node.empty();
}
/** @return the next smallest number */
int next() {
TreeNode* min = node.top();
node.pop();
int val = min->val;
min = min->right;
while(min) {
node.push(min);
min = min->left;
}
return val;
}
private:
stack<TreeNode*> node;
};
/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/