首页 > 代码库 > [LeetCode] 173. Binary Search Tree Iterator Java
[LeetCode] 173. Binary Search Tree Iterator 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.
题意及分析:给出一个二叉排序树,求一个该二叉树的遍历器,满足:(1)hasNext()判断树中是否存在一个除了当前数的最小数。 (2)next()返回树中除了当前数的最小数。(3)要求o(1)的时间复杂度和o(h)的空间复杂度。使用一个栈保存即可,初始保存从根节点到最左节点的值,对于next,如果stack非空就存在hasnext smallest number;对于next,下一个最小的就是栈顶的值(因为该栈顶点的左子节点就是当前点,而栈顶点的右子树上的点肯定比栈顶点大),取出栈顶的点,然后对该点的右子节点左上面的操作(即遍历该点到该点的最左叶节点)。
代码:
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class BSTIterator { private Stack<TreeNode> stack; public BSTIterator(TreeNode root) { stack = new Stack<>(); TreeNode cur = root; while(cur != null){ stack.push(cur); if(cur.left != null) cur = cur.left; else break; } } /** @return whether we have a next smallest number */ public boolean hasNext() { return !stack.isEmpty(); } /** @return the next smallest number */ public int next() { TreeNode node = stack.pop(); TreeNode cur = node; // traversal right branch if(cur.right != null){ cur = cur.right; while(cur != null){ stack.push(cur); if(cur.left != null) cur = cur.left; else break; } } 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 Java
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。