zoukankan      html  css  js  c++  java
  • 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.

    Example:

    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
    /**
     * 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>();
            //Point to the next smallest element.
            this.index = -1;
            //Call to flatten the input BST.
            this.inorder(root);
        }
        
        /** @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();
        }
        
        //inorder traverse
        public void inorder(TreeNode root){
            if(root == null){
                return;
            }
            
            this.inorder(root.left);
            this.nodesSorted.add(root.val);
            this.inorder(root.right);
        }
    }
    
    /**
     * Your BSTIterator object will be instantiated and called as such:
     * BSTIterator obj = new BSTIterator(root);
     * int param_1 = obj.next();
     * boolean param_2 = obj.hasNext();
     */

    BST:左边的总小于root,右边的总大于root

    next总返回最小的,说明是inorder traverse,先用中序flatten BST到一个arraylist,然后get第一个元素即可。

  • 相关阅读:
    Python shutil模块
    Flask 上传文件
    Flask DBUtils
    flash-session
    Flash 上下文管理
    python 栈
    python 偏函数
    threding.local
    next() 与 nextLine() 区别
    Thread.sleep(1000*3); // 休眠3秒
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11427483.html
Copyright © 2011-2022 走看看