LeetCode 173. Binary Search Tree Iterator

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class BSTIterator {
11 
12 public:
13     stack<TreeNode*> stk;
14     BSTIterator(TreeNode *root) {
15         pushNode(root);
16     }
17 
18     /** @return whether we have a next smallest number */
19     bool hasNext() {
20         return !stk.empty();
21     }
22 
23     /** @return the next smallest number */
24     int next() {
25         TreeNode* min = stk.top();
26         stk.pop();
27         pushNode(min->right);
28         return min->val;
29     }
30     
31     void pushNode(TreeNode* root){
32         while(root != NULL){
33             stk.push(root);
34             root = root->left;
35         }
36     }
37     
38 };
39 
40 /**
41  * Your BSTIterator will be called like this:
42  * BSTIterator i = BSTIterator(root);
43  * while (i.hasNext()) cout << i.next();
44  */

hasNext() next()其实都是指当前树中

 

 

题意存疑,留坑。

Your input
[5,0,10,#,#,9,11]

Expected answer
[0,0,0,5,9,10,11]
posted @ 2016-03-02 20:25  co0oder  阅读(160)  评论(0编辑  收藏  举报