1. 程式人生 > 實用技巧 >0173. Binary Search Tree Iterator (M)

0173. Binary Search Tree Iterator (M)

Binary Search Tree Iterator (M)

題目

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.

Example:

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:

  • next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
  • You may assume that 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)\)

思路

如果沒有複雜度限制,那麼最簡單的方法就是先一遍中序遍歷將所有值記錄下來,呼叫next()時挨個返回就行。空間複雜度為\(O(h)\),做法就參考中序遍歷的迭代實現:初始化時先將最左側的邊儲存下來,每次呼叫next()時,棧頂元素就是下一個應返回的結點,出棧後將該結點右子樹的最左側邊存入棧。重複上述過程,棧中元素數量最大為樹高,且查詢平均複雜度為\(O(1)\)


程式碼實現

Java

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();
    }
}

JavaScript

/**
 * 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
}