LeetCode-173. Binary Search Tree Iterator (JAVA)BST的迭代
来源:互联网 发布:软件代理加盟 编辑:程序博客网 时间:2024/05/24 07:35
173. Binary Search Tree Iterator
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, whereh is the height of the tree.
本题目的本质是二叉树的中序遍历
public class BSTIterator {private Stack<TreeNode> stk;public BSTIterator(TreeNode root) {stk = new Stack<>();// 先找到第一个节点,并把路径入栈while (root != null) {stk.push(root);root = root.left;}}/** * @return whether we have a next smallest number */public boolean hasNext() {// 栈为空时不再有下一个return !stk.isEmpty();}/** * @return the next smallest number */public int next() {TreeNode curr = stk.pop();int res = curr.val;// 如果该元素有右节点,把它的右节点及右节点的所有左边节点都压入栈中curr = curr.right;while (curr != null) {stk.push(curr);curr = curr.left;}return res;}}
二叉树的中序遍历非递归
public List<Integer> inorderTraversal(TreeNode root) { List<Integer> list = new ArrayList<>(); if (root == null) return list; Stack<TreeNode> stack = new Stack<>(); while (root != null || !stack.isEmpty()) { if (root != null) { stack.push(root); root = root.left; } else { root = stack.pop(); list.add(root.val); root = root.right; } } return list; }
0 0
- LeetCode-173. Binary Search Tree Iterator (JAVA)BST的迭代
- leetcode java Binary Search Tree Iterator
- [leetcode-173]Binary Search Tree Iterator(java)
- LeetCode|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
- 173. Binary Search Tree Iterator LeetCode
- [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 OJ> 173. Binary Search Tree Iterator
- [LeetCode]problem 173. Binary Search Tree Iterator
- LeetCode - 173. Binary Search Tree Iterator
- Unity平台的预处理
- hdu 2077 汉诺塔IV (递推)
- SDUT 3563 Swiss-system tournament【思维+模拟】
- 1021. 个位数统计 (15)
- div自适应宽度和高度实现
- LeetCode-173. Binary Search Tree Iterator (JAVA)BST的迭代
- 段错误原因收集
- 1020. 月饼 (25)
- hive 调优
- java 基础思维导图
- leetcode 180. Consecutive Numbers 解题思路
- 十分钟pandas(数据透视、矩阵合并、读写文件)
- 剑指offer(java代码)——变态跳台阶
- 关于c++的一些话题