[LeetCode] 173. Binary Search Tree Iterator Java
Posted BrookLearnData
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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的主要内容,如果未能解决你的问题,请参考以下文章
leetcode 173. Binary Search Tree Iterator
[LeetCode] 173. Binary Search Tree Iterator Java
[LeetCode] 173. Binary Search Tree Iterator_Medium_tag: Binary Search Tree
Leetcode solution 173: Binary Search Tree Iterator
? leetcode 173. Binary Search Tree Iterator 设计迭代器(搜索树)--------- java