https://oj.leetcode.com/problems/binary-search-tree-iterator/node
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.数据结构
解题思路:this
首先必需要知道的是,什么叫binary seach tree?它是一个二叉树,便于搜索的。相似于二分查找的思想,BST的左子树全部节点都《=父节点,右子树全部节点都》=父节点,对父节点的每一个子树也都这样。这是一个递归的定义。spa
还要知道,将一个BST按排序输出,就是对它就行中序遍历。为啥?排序输出就是从小到大输出,固然先输出左子树,而后在本身,再右子树了。即,中序遍历。code
题目要求next()个hasNext()的方法要有O(1)的时间复杂度,也就是常数的。通常而言,要么用数组,能够直接从下标获取值,或者用hashMap。那么就意味着咱们要将这些个值先生成好了存下来。blog
按照这个思路来,预先声明一个队列,用来存中序遍历的结果。以后只要按照这个队列顺序输出就好了。队列空了,hasNext就返回false。排序
这里我用的是迭代的方法进行中序遍历,用递归也能够。这个迭代的写法很是多的面试会要求写,bugfree,很重要。递归
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class BSTIterator { private TreeNode root; private Stack<TreeNode> stack; private LinkedList<Integer> valList; public BSTIterator(TreeNode root) { this.root = root; stack = new Stack<TreeNode>(); valList = new LinkedList<Integer>(); // stack.push(root); //条件很重要 while(stack.size() != 0 || root != null){ if(root != null){ stack.push(root); root = root.left; }else{ if(stack.size() > 0){ root = stack.pop(); valList.offer(root.val); root = root.right; } } } } /** @return whether we have a next smallest number */ public boolean hasNext() { if(valList.size() > 0){ return true; }else{ return false; } } /** @return the next smallest number */ public int next() { return valList.poll(); } } /** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */
但看看题目的要求,next和hasNext方法是O(1)了,可是这个队列花费了O(n)的内存。题目要求花费O(h),h为深度,也就是O(logn)。也就是说不能这么作了。再想。
那我只能用一个数据结构,而不是前面的队列,里面存的元素呢,只能是和这个树的高度线性相关的。想来想去,只能借助inorder遍历中间自己就使用的stack了。
用这个方法来作,其实就是把上面in-order的递归方法分开来写。最下面的注释里也给出了用户调用next和hasNext的方法,每次调用next前都会check一下hasNext。代码以下。
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class BSTIterator { private TreeNode root; private Stack<TreeNode> stack; public BSTIterator(TreeNode root) { this.root = root; stack = new Stack<TreeNode>(); } /** @return whether we have a next smallest number */ public boolean hasNext() { while(root != null){ stack.push(root); root = root.left; } if(stack.size() > 0){ return true; }else{ return false; } } /** @return the next smallest number */ public int next() { root = stack.pop(); int returnValue = root.val; root = root.right; return returnValue; } } /** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */
可是这么作内存是O(h)了,hasNext()却没法达到O(1),也许原题说的是average的状况为O(1),我不知道是否是如此,仍是说最优?