119.Binary Search Tree Iterator
来源:互联网 发布:mac os x 10.12 cdr 编辑:程序博客网 时间:2024/05/19 13:59
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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
给定一个二叉查找树,实现该二叉树的hashNext方法和next方法。
调用方法为:
/** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */
public class BSTIterator { int current = 0;//表示当前要遍历的元素int size = 0;//表示二叉查找树中结点总数List<Integer> nodeList = new ArrayList<Integer>(); public BSTIterator(TreeNode root) { if(root != null){ nodeList = inorderTraversal(root); size = nodeList.size(); //System.out.println("nodeList = "+nodeList); } } /** @return whether we have a next smallest number */ public boolean hasNext() { return current < size; } /** @return the next smallest number */ public int next() { return nodeList.get(current++); } /** * 中序遍历二叉查找树 */public List<Integer> inorderTraversal(TreeNode root){List<Integer> list = new ArrayList<Integer>();if(root == null){return list;}else{TreeNode node = root; Stack stack = new Stack();stack.push(node);/*node表示入栈的元素,popnode表示弹栈的元素*/while(!stack.isEmpty()){if(node.left != null){node = node.left;stack.push(node);}else{TreeNode popnode= (TreeNode) stack.pop();//弹出栈顶元素list.add(popnode.val);/*如果弹栈的元素有右孩子,则让其右孩子入栈,进行下一次循环*/if(popnode.right != null){node = popnode.right;stack.push(node);}}}}return list;}}
0 0
- 119.Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Android Graphic SurfaceFlinger分析
- JAVA三大框架SSH的各自作用
- iOS之真机调试的情况下获取并查看数据库
- Java 关于加密哪些事儿
- Java设计模式之缺省模式
- 119.Binary Search Tree Iterator
- IOS 警告 汇总
- java生成图片验证码--公用
- 推荐几款git管理工具
- xml入门
- Java设计模式之模板方法设计模式
- 程序员技术练级攻略
- css中解决textarea高度随内容自适应的问题
- 日志拦截AOP,当执行抛异常时@AfterThrowing执行了没效果