[leetcode]173. 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.

思路:

代码:

 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     
13     private TreeNode cur;
14     private Stack<TreeNode> stack;
15 
16     public BSTIterator(TreeNode root) {
17         cur = root;
18         stack = new Stack<>();
19         
20     }
21 
22     /** @return whether we have a next smallest number */
23     public boolean hasNext() {
24         if(!stack.isEmpty()|| cur!=null) return true;
25         return false;
26     }
27 
28     /** @return the next smallest number */
29     public int next() {   
30       while(cur!=null){
31           stack.push(cur);
32           cur = cur.left;
33       }
34         cur = stack.pop();
35         int val = cur.val;
36         cur = cur.right;
37         return val;     
38     }
39 }
40 
41 /**
42  * Your BSTIterator will be called like this:
43  * BSTIterator i = new BSTIterator(root);
44  * while (i.hasNext()) v[f()] = i.next();
45  */

猜你喜欢

转载自www.cnblogs.com/liuliu5151/p/9810155.html