[LeetCode 173] Binary Search Tree Iterator
来源:互联网 发布:编程语言排行榜2017 8 编辑:程序博客网 时间:2024/06/04 17:54
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.
Solution:
Use the stack to store left most node in the BST.
Top element is the smalleset one, and pop it out. store its right child's left node.
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class BSTIterator { Stack<TreeNode> nodePath = new Stack<>(); public BSTIterator(TreeNode root) { while(!nodePath.isEmpty()) nodePath.clear(); TreeNode n1 = root; while(n1!=null){ nodePath.add(n1); n1 = n1.left; } } /** @return whether we have a next smallest number */ public boolean hasNext() { return !nodePath.empty(); } /** @return the next smallest number */ public int next() { TreeNode n1 = nodePath.pop(); int res = n1.val; n1 = n1.right; while(n1!=null){ nodePath.push(n1); n1 = n1.left; } return res; }}/** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */
0 0
- leetcode 173: Binary Search Tree Iterator
- leetcode-173 Binary Search Tree Iterator
- Leetcode[173]-Binary Search Tree Iterator
- LeetCode(173) Binary Search Tree Iterator
- [LeetCode 173] Binary Search Tree Iterator
- [leetcode-173]Binary Search Tree Iterator(java)
- 【LEETCODE】173-Binary Search Tree Iterator
- LeetCode—173 Binary Search Tree Iterator
- leetcode #173 Binary Search Tree Iterator
- LeetCode(173) Binary Search Tree Iterator
- 【leetcode】【173】Binary Search Tree Iterator
- 【LeetCode-173】Binary Search Tree Iterator
- Leetcode 173: Binary Search Tree Iterator
- LeetCode[173] Binary Search Tree Iterator
- LeetCode No.173 Binary Search Tree Iterator
- LeetCode #173 - Binary Search Tree Iterator - Medium
- [Leetcode] #173 Binary Search Tree Iterator
- Leetcode 173 Binary Search Tree Iterator
- HDOJ 5410 CRB and His Birthday DP背包
- inux重定向及nohup不输出的方法
- mybatis之foreach用法
- 简单路由器的实现
- VMware与主机三种通信方式
- [LeetCode 173] Binary Search Tree Iterator
- Spring 3 JavaConfig @Import example
- springmvc学习笔记(一)第一个helloworld
- MapReduce实现join操作
- JSFF2 mount fail
- gitlab 使用postgresql数据库的一些说明
- TS流判断I帧
- poj 1129 Channel Allocation(DFS减枝)
- 基于Spring可扩展Schema提供自定义配置支持(spring配置文件中 配置标签支持)