标签:
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.
中午下雨了。于是木有吃午饭(=。=)现在有点饿。
这个比较难的就是next() method了,就是喊你返回BTS中最小的那个数。
然后很容易的,我们要先建一个不管是List,stack还是神马的,反正拿来store每个结点最小的数就行了。(一般情况下就是最左边的那个数)
当然呢如果最左边刚好null呢?我们第一次store的时候就肯定会在这里停下了,因此我们需要检查右边是否null,如果右边不是null的,那么就检查这个右边的treenode左边是否null,如果是,继续接着往下…………
代码如下。~
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class BSTIterator { List<TreeNode> tree; public BSTIterator(TreeNode root) { tree=new ArrayList<TreeNode>(); while(root!=null){ tree.add(root); root=root.left; } } /** @return whether we have a next smallest number */ public boolean hasNext() { return !tree.isEmpty(); } /** @return the next smallest number */ public int next() { TreeNode min=tree.remove(tree.size()-1); TreeNode temp=min.right; while(temp!=null){ tree.add(temp); temp=temp.left; } return min.val; } } /** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */
[LeetCode] Binary Search Tree Iterator
标签:
原文地址:http://www.cnblogs.com/orangeme404/p/4729843.html