前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode <dfs>173.Binary Search Tree Iterator

LeetCode <dfs>173.Binary Search Tree Iterator

原创
作者头像
大学里的混子
修改2018-11-15 14:51:12
4170
修改2018-11-15 14:51:12
举报
文章被收录于专栏:LeetCodeLeetCode

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.

Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.

题目大意:实现二分搜索树的迭代器。

解法:

思路:由于二分搜索树的中序遍历是从小到大顺序排列的数列,只需要采用一个栈存储遍历的数据,然后当迭代器需要获得下一个元素的时候就将栈里面的元素弹出即可。

代码语言:javascript
复制
public class BSTIterator {
     Stack<TreeNode> stack;
    public BSTIterator(TreeNode root) {
        stack = new Stack<TreeNode>(); // initialize the stack
        stackHelper(root);
    }

    public void stackHelper(TreeNode root){
        if (root == null) return;
        stackHelper(root.right); 
        stack.push(root);
        stackHelper(root.left);      
    }

    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        return !stack.isEmpty();
    }

    /** @return the next smallest number */
    public int next() {
        return stack.pop().val;
    }
}

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 173.Binary Search Tree Iterator
    • 解法:
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
    http://www.vxiaotou.com