1. 程式人生 > >【一次過】Lintcode 86. 二叉查詢樹迭代器

【一次過】Lintcode 86. 二叉查詢樹迭代器

設計實現一個帶有下列屬性的二叉查詢樹的迭代器:
next()返回BST中下一個最小的元素

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

樣例

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

   10
 /    \
1      11
 \       \
  6       12

挑戰

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

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


解題思路:

非遞迴中序遍歷的變形。

/**
 * 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 List<TreeNode> list = new ArrayList<>();
    private int i = 0;
    /*
    * @param root: The root of binary tree.
    */public BSTIterator(TreeNode root) {
        // do intialization if necessary
        Stack<TreeNode> stack = new Stack<>();
        
        while(root!=null || !stack.isEmpty()){
            while(root != null){
                stack.push(root);
                root = root.left;
            }
            
            root = stack.pop();
            
            list.add(root);
            
            root = root.right;
        }
    }

    /*
     * @return: True if there has next node, or false
     */
    public boolean hasNext() {
        // write your code here
        if(i < list.size())
            return true;
        else
            return false;
    }

    /*
     * @return: return next node
     */
    public TreeNode next() {
        // write your code here
        return list.get(i++);
    }
}