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.
中午下雨了。于是木有吃午飯(=。=)現在有點餓。
這個比較難的就是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(); */新聞熱點
疑難解答