Binary Tree Inorder Traversal, Binary Search Tree Iterator
来源:互联网 发布:编程导论 梁杰 pdf 编辑:程序博客网 时间:2024/05/13 18:40
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.
首先 in order traversal
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
Stack<TreeNode> parentStack = new Stack<TreeNode>();
ArrayList<Integer> result = new ArrayList<Integer>();
while(root!=null||!parentStack.isEmpty()){
while(root!=null){
parentStack.push(root);
root=root.left;
}
root = parentStack.pop();
result.add(root.val);
root = root.right;
}
return result;
}
}
然后 Binary Search Tree Iterator
public class BSTIterator {
Stack<TreeNode> parentstack = new Stack<>();
TreeNode crt ;
public BSTIterator(TreeNode root) {
crt = root;
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return (crt!=null || !parentstack.isEmpty());
}
/** @return the next smallest number */
public int next() {
int result=0;
while(crt!=null){
parentstack.push(crt);
crt=crt.left;
}
crt = parentstack.pop();
result = crt.val;
crt= crt.right;
return result;
}
}
- Binary Tree Inorder Traversal, Binary Search Tree Iterator
- Binary tree inorder iterator
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- 动态改变Google Admob 大小,宽高
- 正能量 读书笔记
- POJ 2385 Apple Catching (dp)
- FFmpeg源代码简单分析:avformat_close_input()
- poj3420 棋盘覆盖
- Binary Tree Inorder Traversal, Binary Search Tree Iterator
- Fragment使用(二),FragmentTransaction管理Fragment
- 几个比较强大的工具
- 7,Reverse Integer
- qt5学习问题笔记二(从零开始)
- POJ 3616 Milking Time (dp)
- PSR-4 实例
- linux下终端之间的切换
- POJ 3280 Cheapest Palindrome (dp)