LeetCode 173. Binary Search Tree Iterator

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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]

以上是关于LeetCode 173. Binary Search Tree Iterator的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 173. Binary Search Tree Iterator

[LeetCode] 173. Binary Search Tree Iterator Java

[LeetCode] 173. Binary Search Tree Iterator_Medium_tag: Binary Search Tree

Leetcode solution 173: Binary Search Tree Iterator

? leetcode 173. Binary Search Tree Iterator 设计迭代器(搜索树)--------- java

LeetCode 173. Binary Search Tree Iterator(搜索二叉树)