• 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第一个元素即可。

  • 相关阅读:
    SQL 存储过程分页
    SqlServer中代理作业实现总结
    firfox兼容性插件
    C#停靠栏组件 DockPanel Suite
    Web.Config加密
    osql
    prototype.js的Ajax对IE8兼容问题解决方案
    获取系统的字体
    基于RBAC的权限管理系统的实现经典
    c/s(C#)下Ftp的多文件上传及其上传进度
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11427483.html
Copyright © 2020-2023  润新知