Binary Search Tree Iterator

原题: https://leetcode.com/problems/binary-search-tree-iterator/description/

题意: 实现一个二叉搜索树(BST)的迭代器。你的迭代器会使用BST的根节点初始化。调用next()会返回BST中下一个最小的数字。

约定:(1)next()和hasNext()应该满足平均O(1)时间复杂度和O(h)空间复杂度,其中h是树的高度。

标签: bst、iterator、binary、search、tree、面试
猜你感兴趣的圈子:
LeetCode交流圈
  • Bingo
    2017-08-17 16:36:08 1楼#1层
    Python:
    class BSTIterator:
        # @param root, a binary search tree's root node
        def __init__(self, root):
            self.stack = []
            self.pushLeft(root)
    
        # @return a boolean, whether we have a next smallest number
        def hasNext(self):
            return self.stack
    
        # @return an integer, the next smallest number
        def next(self):
            top = self.stack.pop()
            self.pushLeft(top.right)
            return top.val
        
        def pushLeft(self, node):
            while node:
                self.stack.append(node)
                node = node.left
  • Bingo
    2017-08-17 16:36:34 2楼#1层
    C++:
    class BSTIterator {
    public:
        BSTIterator(TreeNode *root) {
            while (root) {
                s.push(root);
                root = root->left;
            }
        }
    
        /** @return whether we have a next smallest number */
        bool hasNext() {
            return !s.empty();
        }
    
        /** @return the next smallest number */
        int next() {
            TreeNode *n = s.top();
            s.pop();
            int res = n->val;
            if (n->right) {
                n = n->right;
                while (n) {
                    s.push(n);
                    n = n->left;
                }
            }
            return res;
        }
    private:
        stack<TreeNode*> s;
    };
  • Bingo
    2017-08-17 16:37:15 3楼#1层
    Java:
    public class BSTIterator {
        private Stack<TreeNode> stack = new Stack<TreeNode>();
        
        public BSTIterator(TreeNode root) {
            pushAll(root);
        }
    
        /** @return whether we have a next smallest number */
        public boolean hasNext() {
            return !stack.isEmpty();
        }
    
        /** @return the next smallest number */
        public int next() {
            TreeNode tmpNode = stack.pop();
            pushAll(tmpNode.right);
            return tmpNode.val;
        }
        
        private void pushAll(TreeNode node) {
            for (; node != null; stack.push(node), node = node.left);
        }
    }
  • 回复
隐藏