Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.javascript
Calling next()
will return the next smallest number in the BST.java
Example:node
BSTIterator iterator = new BSTIterator(root); iterator.next(); // return 3 iterator.next(); // return 7 iterator.hasNext(); // return true iterator.next(); // return 9 iterator.hasNext(); // return true iterator.next(); // return 15 iterator.hasNext(); // return true iterator.next(); // return 20 iterator.hasNext(); // return false
Note:this
next()
and hasNext()
should run in average O(1) time and uses O(h) memory, where h is the height of the tree.next()
call will always be valid, that is, there will be at least a next smallest number in the BST when next()
is called.實現一個BST迭代器,要求next()和hasNext()的平均時間複雜度爲\(O(1)\)且空間複雜度爲\(O(h)\)。spa
若是沒有複雜度限制,那麼最簡單的方法就是先一遍中序遍歷將全部值記錄下來,調用next()時挨個返回就行。空間複雜度爲\(O(h)\),作法就參考中序遍歷的迭代實現:初始化時先將最左側的邊存儲下來,每次調用next()時,棧頂元素就是下一個應返回的結點,出棧後將該結點右子樹的最左側邊存入棧。重複上述過程,棧中元素數量最大爲樹高,且查詢平均複雜度爲\(O(1)\)。prototype
class BSTIterator { private Deque<TreeNode> stack; private int index; public BSTIterator(TreeNode root) { stack = new ArrayDeque<>(); while (root != null) { stack.push(root); root = root.left; } } /** * @return the next smallest number */ public int next() { TreeNode node = stack.pop(); TreeNode tmp = node.right; while (tmp != null) { stack.push(tmp); tmp = tmp.left; } return node.val; } /** * @return whether we have a next smallest number */ public boolean hasNext() { return !stack.isEmpty(); } }
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root */ var BSTIterator = function (root) { this.stack = [] while (root) { this.stack.push(root) root = root.left } } /** * @return {number} */ BSTIterator.prototype.next = function () { let top = this.stack.pop() let p = top.right while (p) { this.stack.push(p) p = p.left } return top.val } /** * @return {boolean} */ BSTIterator.prototype.hasNext = function () { return this.stack.length }