leetcode------Binary Search Tree Iterator

标题: Binary Search Tree Iterator
通过率: 28.9%
难度: 中等

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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

就是非递归中序遍历二叉树:

代码如下:

 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     TreeNode node=null;

13     Stack<TreeNode> stack=new Stack<TreeNode>();

14     public BSTIterator(TreeNode root) {

15         if(root!=null){

16             stack.push(root);

17             node=root;

18             while(node.left!=null){

19                 stack.push(node.left);

20                 node=node.left;

21             }

22         }

23     }

24 

25     /** @return whether we have a next smallest number */

26     public boolean hasNext() {

27         if(!stack.isEmpty())return true;

28         else return false;

29     }

30 

31     /** @return the next smallest number */

32     public int next() {

33         node=stack.pop();

34         int res=node.val;

35         if(node.right!=null){

36             stack.push(node.right);

37             node=node.right;

38             while(node.left!=null){

39                 stack.push(node.left);

40                 node=node.left;

41             }

42         }

43         return res;

44     }

45 }

46 

47 /**

48  * Your BSTIterator will be called like this:

49  * BSTIterator i = new BSTIterator(root);

50  * while (i.hasNext()) v[f()] = i.next();

51  */

 

你可能感兴趣的:(Binary search)