1. 程式人生 > >lintcode(86)二叉查詢樹迭代器

lintcode(86)二叉查詢樹迭代器

Description:

設計實現一個帶有下列屬性的二叉查詢樹的迭代器:

  • 元素按照遞增的順序被訪問(比如中序遍歷)
  • next()hasNext()的詢問操作要求均攤時間複雜度是O(1)

Explanation:

對於下列二叉查詢樹,使用迭代器進行中序遍歷的結果為 [1, 6, 10, 11, 12]

   10
 /    \
1      11
 \       \
  6       12

Challenge:

額外空間複雜度是O(h),其中h是這棵樹的高度

Super Star:使用O(1)的額外空間複雜度

 Solution:

使用堆疊記錄當前root 中序遍歷的路徑,將左節點從上至下推入到堆疊中。

堆疊非空,則有下一個節點。

next就是將堆疊中的節點依次進行中序遍歷,返回當前節點,並將後來中序遍歷的左節點推入棧中。

/**
 * 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 {
    //@param root: The root of binary tree.
    Stack<TreeNode> tree = new Stack<TreeNode>();
    
    public BSTIterator(TreeNode root) {
        // write your code here
        while(root != null){
            tree.push(root);
            root = root.left;
        }
    }

    //@return: True if there has next node, or false
    public boolean hasNext() {
        // write your code here
        return !tree.isEmpty();
    }
    
    //@return: return next node
    public TreeNode next() {
        // write your code here
        TreeNode result = tree.pop();
        TreeNode current =  result;
        
        if(current.right != null){
            current = current.right;
            while(current != null){
                tree.push(current);
                current = current.left;
            }
        }
        
        return result;
    }
}