LeetCode 173. Binary Search Tree Iterator

原题链接在这里:https://leetcode.com/problems/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.

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.

题解:

用一个stack把所有最左边的node压进 stack中。

判断hasNext()时就是看stack 是否为空.

next()返回stack顶部top元素,若是top有右子树,就把右子树的所有最左node压入stack中.

constructor time complexity: O(h).

hashNext time complexity: O(1).

next time complexity: O(h).

Space: O(h), stack 最大为树的高度。

AC Java:

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 
11 public class BSTIterator {
12     Stack<TreeNode> stk;
13     
14     public BSTIterator(TreeNode root) {
15         stk = new Stack<TreeNode>();
16         while(root != null){
17             stk.push(root);
18             root = root.left;
19         }
20     }
21 
22     /** @return whether we have a next smallest number */
23     public boolean hasNext() {
24         return !stk.isEmpty();
25     }
26 
27     /** @return the next smallest number */
28     public int next() {
29         TreeNode top = stk.pop();
30         TreeNode rightLeft = top.right;
31         while(rightLeft != null){
32             stk.push(rightLeft);
33             rightLeft = rightLeft.left;
34         }
35         
36         return top.val;
37     }
38 }
39 
40 /**
41  * Your BSTIterator will be called like this:
42  * BSTIterator i = new BSTIterator(root);
43  * while (i.hasNext()) v[f()] = i.next();
44  */

类似All Elements in Two Binary Search TreesBinary Tree Inorder TraversalInorder Successor in BST.  

posted @ 2016-02-22 02:55  Dylan_Java_NYC  阅读(268)  评论(0编辑  收藏  举报