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

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class BSTIterator {
        private LinkedList<TreeNode> stack;
        private TreeNode cur;
        public BSTIterator(TreeNode root) {
            stack = new LinkedList<>();
            cur = root;
        }
        
        /** @return the next smallest number */
        public int next() {
            while (cur != null) {
                stack.offerFirst(cur);
                cur = cur.left;
            }
            cur = stack.pollFirst();
            int val = cur.val;
            cur = cur.right;
            return val;
        }
        
        /** @return whether we have a next smallest number */
        public boolean hasNext() {
            return !stack.isEmpty() || cur != null;
        }
    }
    
    /**
     * 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();
     */
  • 相关阅读:
    Mysql实战面试题
    初探Google Guava
    Spring IOC核心源码学习
    用3句话像老太太讲清楚什么是数据库
    matlab如何读入mat型的矩阵
    工作记忆数据处理
    功能连接
    奖励学习
    格兰杰因果关系及其在医学影像数据中的应用
    GC wm
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12199077.html
Copyright © 2011-2022 走看看