Leetcode 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.

這道題主要考察利用Stack對BFS實現inorder traverse.

public class BSTIterator {
    //use this stack to push the treeNode into the stack.
    Stack<TreeNode> stack = Stack<TreeNode>();

    public BSTIterator(TreeNode root) {
      treeNode tem = root;
      //first judge if the node is null, then if the node is not null, then push it into the stack
      while(tem != null){
        stack.push(tem);
        tem = tem.left;
      }
    }

    /** @return whether we have a next smallest number */
    public boolean hasNext() {
      return !stack.isEmpty();
    }

    /** @return the next smallest number */
    public int next() {
      TreeNode minimum = (TreeNode)stack.pop();
      int result = minimum.val;
      TreeNode tem = minimum.right;
      while(tem != null){
        stack.push(tem);
        tem = tem.left;
      }
      return result;
    }
}


發佈了123 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章