Binary Search Tree Iterator
来源:互联网 发布:汝窑茶具 淘宝 编辑:程序博客网 时间:2024/05/22 06:07
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.
接着上一题,这题考察的是中序遍历。用的方法跟上面那道题的思路是相同的。
中序遍历的思路是使用一个栈,将它以及它的左孩子压入栈。每次弹栈的时候,判断是否存在右孩子,如果存在的话,对右孩子进行相同的操作,把右孩子以及右孩子的左孩子压入栈。
代码:
Stack<TreeNode> stack; TreeNode root; public BSTIterator(TreeNode root) { stack = new Stack<>(); this.root = root; //init the stack by pushing left nodes into the stack pushToStack(root); } private void pushToStack(TreeNode node){ if(node == null) return; stack.push(node); while(node.left != null){ node = node.left; stack.push(node); } } /** @return whether we have a next smallest number */ public boolean hasNext() { return !stack.isEmpty(); } /** @return the next smallest number */ public int next() { //needs null pointer handling if(!hasNext()) return -1; TreeNode node = stack.pop(); if(node.right!= null){ pushToStack(node.right); } return node.val; }
0 0
- 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
- 为什么说java是“一次编译到处运行?”
- 怎样查找端口是否被占用,被谁占用
- 2016,梦想起航
- linux驱动:TI+DM8127+GPIO(四)之设备
- Android开发中SQLite数据库操作(二)
- Binary Search Tree Iterator
- Hasher Pro v3.3
- mongodb安装
- VS2012必须用附加到进程,不能本机调试
- 浏览器渲染原理
- c++中extern的用法
- linux驱动:TI+DM8127+GPIO(五)之plarform
- C++串口操作以及串口模拟测试
- android hook研究