Binary Search Tree Iterator

Description

Design an iterator over a binary search tree with the following rules:
  • Elements are visited in ascending order (i.e. an in-order traversal)
  • next() and hasNext() queries run in O(1) time in average.

Example

Example 1java

Input:  {10,1,11,#,6,#,12}
Output:  [1, 6, 10, 11, 12]
Explanation:
The BST is look like this:
  10
  /\
 1 11
  \  \
   6  12
You can return the inorder traversal of a BST [1, 6, 10, 11, 12]
/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 * Example of iterate a tree:
 * BSTIterator iterator = new BSTIterator(root);
 * while (iterator.hasNext()) {
 *    TreeNode node = iterator.next();
 *    do something for node
 * } 
 */


public class BSTIterator {
    private Stack<TreeNode> stack = new Stack<>();
    
    // @param root: The root of binary tree.
    public BSTIterator(TreeNode root) {
        while (root != null) {
            stack.push(root);
            root = root.left;
        }
    }

    //@return: True if there has next node, or false
    public boolean hasNext() {
        return !stack.isEmpty();
    }
    
    //@return: return next node
    public TreeNode next() {
        TreeNode curt = stack.peek();
        TreeNode node = curt;
        
        // move to the next node
        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;
    }
}

  

Example 2node

Input: {2,1,3}
Output: [1,2,3]
Explanation:
The BST is look like this:
  2
 / \
1   3
You can return the inorder traversal of a BST tree [1,2,3]

Challenge

Extra memory usage O(h), h is the height of the tree.算法

Super Star: Extra memory usage O(1)markdown

 

思路:app

這是一個很是通用的利用 stack 進行 Binary Tree Iterator 的寫法。this

stack 中保存一路走到當前節點的全部節點,stack.peek() 一直指向 iterator 指向的當前節點。
所以判斷有沒有下一個,只須要判斷 stack 是否爲空
得到下一個值,只須要返回 stack.peek() 的值,並將 stack 進行相應的變化,挪到下一個點。code

挪到下一個點的算法以下:blog

  1. 若是當前點存在右子樹,那麼就是右子樹中「一路向西」最左邊的那個點
  2. 若是當前點不存在右子樹,則是走到當前點的路徑中,第一個左拐的點

訪問全部節點用時O(n),因此均攤下來訪問每一個節點的時間複雜度時O(1)ip

相關文章
相關標籤/搜索