173.Binary-Search-Tree-Iterator

173. Binary Search Tree Iterator

题目地址

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

http://www.lintcode.com/en/problem/binary-search-tree-iterator/

http://www.jiuzhang.com/solutions/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.

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.

代码

Approach #0 Controlled Recursion

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode(int x) { val = x; }
 * }
 */
class BSTIterator {

    Stack<TreeNode> stack;

    public BSTIterator(TreeNode root) {

        // Stack for the recursion simulation
        this.stack = new Stack<TreeNode>();

        // Remember that the algorithm starts with a call to the helper function
        // with the root node as the input
        _leftmostInorder(root);
    }

    private void _leftmostInorder(TreeNode root) {

        // For a given node, add all the elements in the leftmost branch of the tree
        // under it to the stack.
        while (root != null) {
            this.stack.push(root);
            root = root.left;
        }
    }

    /**
     * @return the next smallest number
     */
    public int next() {
        // Node at the top of the stack is the next smallest element
        TreeNode topmostNode = this.stack.pop();
        // Need to maintain the invariant. If the node has a right child, call the 
        // helper function for the right child
        if (topmostNode.right != null) {
            this._leftmostInorder(topmostNode.right);
        }

        return topmostNode.val;
    }

    /**
     * @return whether we have a next smallest number
     */
    public boolean hasNext() {
        return this.stack.size() > 0;
    }
}

Approach 1: Using Stack

public class BSTIterator {
   private Stack<TreeNode> stack = new Stack<>();

  public BSTIterator(TreeNode root) {
    while (root != null) {
      stack.push(root);
      root = root.left;
    }
  }

  public boolean hasNext() {
    return !stack.isEmpty();
  }

  public TreeNode next() {
    TreeNode curt = stack.peek();
    TreeNode node = curt;

    if (node.right == null) {
      node = stack.pop();    // 右子树为空才会弹出
      while (!stack.isEmpty() && stack.peek().right == node) {
        node = stack.pop();
      }
    } else {
      node = node.right;
      while (node != null) {
        stack.push(node);
        node = node.left;
      }
    }

    return curt; // 注意题目其实要求返回的是 curt.val
  }
}

Approach 2:

class BSTIterator {
  private Stack<TreeNode> stack = new Stack<>();
  TreeNode next = null;

  public BSTIterator(TreeNode root) {
    next = root;
  }

  public boolean hasNext() {
       while (next != null) {
      stack.push(next);
      next = next.left;
     }
    return !stack.isEmpty();
  }

    private void AddNodeToStack(TreeNode root) {
    while (root != null) {
      stack.push(root);
      root = root.left;
    }
  }

  public TreeNode next() {
    if (!hasNext()) {
      return null;
    }
    TreeNode cur = stack.pop();
    next = cur.right;
    return cur;
  }
}

Approach #3 Flattening the BST

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode(int x) { val = x; }
 * }
 */
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode(int x) { val = x; }
 * }
 */
class BSTIterator {
    ArrayList<Integer> nodesSorted;
    int index;

    public BSTIterator(TreeNode root) {

        // Array containing all the nodes in the sorted order
        this.nodesSorted = new ArrayList<Integer>();

        // Pointer to the next smallest element in the BST
        this.index = -1;

        // Call to flatten the input binary search tree
        this._inorder(root);
    }

    private void _inorder(TreeNode root) {
        if (root == null) {
            return;
        }

        this._inorder(root.left);
        this.nodesSorted.add(root.val);
        this._inorder(root.right);
    }

    /**
     * @return the next smallest number
     */
    public int next() {
        return this.nodesSorted.get(++this.index);
    }

    /**
     * @return whether we have a next smallest number
     */
    public boolean hasNext() {
        return this.index + 1 < this.nodesSorted.size();
    }
}

Last updated