173. Binary Search Tree Iterator(中序遍历)



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.

 

 

class BSTIterator {
public:
    stack<TreeNode*> stk;
    TreeNode* cur;
    BSTIterator(TreeNode* root) {
        cur = root;
    }
    
    int next() {
        int ret;
        while(cur != nullptr) {
            stk.push(cur);
            cur = cur->left;
        }
        cur = stk.top();
        stk.pop();
        ret = cur->val;
        cur = cur->right;
        return ret;
    }
    
    bool hasNext() {
        return (cur != nullptr || !stk.empty());
    }
};

 

 

 

 

 

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 
11 public class BSTIterator {
12     private Stack<TreeNode> stack = new Stack<TreeNode>();
13     public BSTIterator(TreeNode root) {
14         pushAll(root);
15     }
16 
17     /** @return whether we have a next smallest number */
18     public boolean hasNext() {
19         return !stack.isEmpty();
20     }
21 
22     /** @return the next smallest number */
23     public int next() {
24         TreeNode node = stack.pop();
25         pushAll(node.right);
26         return node.val;
27         
28     }
29     private void pushAll(TreeNode node){
30         while(node != null){
31             stack.push(node);
32             node = node.left;
33         }
34             
35     }
36 }
37 
38 /**
39  * Your BSTIterator will be called like this:
40  * BSTIterator i = new BSTIterator(root);
41  * while (i.hasNext()) v[f()] = i.next();
42  */

 

 

posted @ 2018-02-01 10:53  乐乐章  阅读(135)  评论(0编辑  收藏  举报