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.
Implementation:
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class BSTIterator { private Stack<TreeNode> stack = new Stack<TreeNode>(); public BSTIterator(TreeNode root) { pushLeft(root); } private void pushLeft(TreeNode node) { while(node != null) { stack.push(node); node = node.left; } } /** @return whether we have a next smallest number */ public boolean hasNext() { return !stack.isEmpty(); } /** @return the next smallest number */ public int next() { TreeNode n = stack.pop(); pushLeft(n.right); return n.val; } } /** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */
Reference:
http://classes.engr.oregonstate.edu/eecs/spring2012/cs261/lectures/BST_Iterator.pdf
http://n00tc0d3r.blogspot.com/2013/08/implement-iterator-for-binarytree-i-in.html
相关推荐
java java_leetcode-99-recover-binary-search-tree
java java_leetcode-107-binary-tree-level-order-traversal
java java_leetcode-102-binary-tree-level-order-traversal
java java_leetcode-110-balanced-binary-tree
java java_leetcode-maximum-depth-of-binary-tree
java java_leetcode-114-flatten-binary-tree-to-linked-list
java java_leetcode-111-minimum-depth-of-binary-tree
java java_leetcode-105-construct-binary-tree-from-preorder-and-inorde
LeetCode上的第173题“Binary Search Tree Iterator”便是这样一个问题,它要求设计并实现一个二叉搜索树迭代器类BSTIterator,该迭代器将支持两个操作:`next()` 和 `hasNext()`。`next()` 方法会返回二叉搜索树中...
java java_leetcode-101-symmetric-tree
java java_leetcode-100-same-tree
"leetcode-tag-Tree" 指的是 LeetCode 上与“树”相关的标签,这通常意味着这些题目涉及到数据结构中的树型结构。树是一种非线性的数据结构,由若干个节点(或称为顶点)和连接这些节点的边组成,每个节点都可能有零...
"js-leetcode题解之98-validate-binary-search-tree.js"这道题目是关于如何在JavaScript中验证一个给定的二叉树是否为二叉搜索树的问题。这道题不仅考察了应聘者对二叉搜索树特性的掌握,也考察了他们运用JavaScript...
本项目 "LeetCode-BinarySearch" 显然是围绕这个主题展开,通过 Java 实现来深入理解和掌握二分查找技术。 二分查找的基本思想是利用数组的有序性,将查找范围不断减半,直到找到目标元素或确定目标元素不存在。...
《在IDE中高效进行LeetCode练习:leetcode-editor的深度解析》 在编程学习与技能提升的过程中,LeetCode作为一款广受欢迎的在线编程挑战平台,帮助众多开发者锻炼算法思维,提高编程能力。而为了进一步提升练习体验...
Python-leetcode题解之226-Invert-Binary-Tree.py提供了一个简单直观的解决方案来理解和练习二叉树的翻转操作,是学习数据结构和算法的有益练习。通过这种方式,编程者可以提升自己的编程技巧,并加深对二叉树相关...
leetcode-cli-plugins leetcode-cli 的第 3 方插件。 什么是 如何使用 如何使用 插件 名称 描述 增强的命令 按公司或标签过滤问题 list 不要在同一台计算机上使 Chrome 的会话过期 login 不要在同一台计算机上使 ...
在IDE中解决LeetCode问题,支持leetcode.com与leetcode-cn.com,满足基本的做题需求。 理论上支持: IntelliJ IDEA PhpStorm WebStorm PyCharm RubyMine AppCode CLion GoLand DataGrip Rider MPS Android Studio。
c语言-leetcode题解之0094-binary-tree-inorder-traversal.zip文件将为C语言学习者提供一次深入理解中序遍历算法并实践C语言编码的宝贵机会,尤其适合那些希望通过实际问题来提高编程技能的开发者。