Binary Search Tree Iterator
来源:互联网 发布:csgo查看战绩的软件 编辑:程序博客网 时间:2024/05/21 09:00
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.
对的
代码:
private Stack<TreeNode> stack; private TreeNode root; public BSTIterator(TreeNode root) { this.root = root; stack = new Stack<>(); pushToStack(root); } private void pushToStack(TreeNode node){ if(node == null) return; TreeNode p = node; while(p != null){ stack.push(p); p = p.left; } } /** @return whether we have a next smallest number */ public boolean hasNext() { if(stack.isEmpty()) return false; return true; } /** @return the next smallest number */ public int next() { if(stack.isEmpty()) return -1; TreeNode tree = stack.pop(); if(tree.right != null){ pushToStack(tree.right); } return tree.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
- 薛(学)问天只是证明了Z=Z就误以为证明了Z=L
- 初识Azure
- 创建第一个Azure Liunx虚拟机
- Linux ssh 登陆
- ubuntu创建新用户并增加管理员权限详解
- Binary Search Tree Iterator
- 在Azure上创建MYSQL服务
- 安装各种论坛小记
- 虚拟机连接主机oracle
- MySQL常用语句
- mysql必知必会 - LIMIT
- 二维码系列(四)二维码工具类的封装和使用,非常经典,拿走不谢
- CTF夺旗赛培训——基本知识
- Tricky machine code