Binary Search Tree Iterator 二叉搜索树的迭代器
2015-01-03 08:57
330 查看
题目:
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling
Note:
h is the height of the tree.
用java实现:
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.
用java实现:
// Definition for binary tree class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public class BSTIterator { private Stack<TreeNode> stack = new Stack<TreeNode>(); private TreeNode current = null; public BSTIterator(TreeNode root) { current = root; } /** @return whether we have a next smallest number */ public boolean hasNext() { return (current != null || !stack.isEmpty()); } /** @return the next smallest number */ public int next() { while(current!=null){ stack.push(current); current = current.left; } current = stack.pop(); TreeNode node = current; current = current.right; return node.val; } } /** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */
相关文章推荐
- [leetcode 173] Binary Search Tree Iterator-------为二叉搜索树实现迭代器功能
- 173. Binary Search Tree Iterator -- 迭代器
- Binary Search Tree Iterator 二叉搜索树的遍历
- 实现二分查找树的迭代器(Binary Search Tree Iterator )
- LeetCode|Binary Search Tree Iterator-java
- 173. Binary Search Tree Iterator
- [leetcode][tree][stack] Binary Search Tree Iterator
- 二叉搜索树(Binary Search Tree)--C语言描述(转)
- 119.Binary Search Tree Iterator
- [LeetCode] 173. Binary Search Tree Iterator 二叉搜索树迭代器
- 173. Binary Search Tree Iterator
- [Leetcode] 173. Binary Search Tree Iterator 解题报告
- leetcode -- Binary Search Tree Iterator -- 重点
- [LeetCode] Binary Search Tree Iterator
- 二叉搜索树(Binary Search Tree)
- LeetCode-JAVA-Binary Search Tree Iterator1.
- 编程算法 - 二叉搜索树(binary search tree) 代码(C)
- Java二叉搜索树(Binary Search Tree)实现
- 第九章 ALDS1_8_A:Binary Search Tree I 二叉搜索树--插入
- [LeetCode] Binary Search Tree Iterator 深度搜索