[Java]leetcode173 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.

Callingnext()will return the next smallest number in the BST.

Note:next()andhasNext()should run in average O(1) time and uses O(h) memory, wherehis the height of the tree.

题意:写一个二叉查找树的迭代器,实现hasNext()和next()的功能。next()每次返回二叉树中未访问的最小值。要求的平均时间复杂度是O(1)和空间复杂度是O(h)。

解题思路:next()每次返回二叉树中未访问的最小值。也就是将二叉树中序遍历,并将对应值输出。这里面注意的是空间和时间的复杂度。public class BSTIterator {//将中序遍历的功能嵌查在整个程序中TreeNode current;Stack<TreeNode> stack;public BSTIterator(TreeNode root) {current=root;stack=new Stack<TreeNode>();while(current!=null)//因为只可能是左节点才是最小值,,将所有左子树节点入栈,保证空间复杂度是O(h){stack.push(current);current=current.left;}}/** @return whether we have a next smallest number */public boolean hasNext() {return !stack.isEmpty();}/** @return the next smallest number */public int next() {current=stack.pop();int res=current.val;//这一步已经得到最小值current=current.right;//但要考虑到右子树的遍历while(current!=null){stack.push(current);current=current.left;}return res;}}

美好的生命应该充满期待、惊喜和感激

[Java]leetcode173 Binary Search Tree Iterator

相关文章:

你感兴趣的文章:

标签云: