119.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.

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

Subscribe to see which companies asked this question

给定一个二叉查找树,实现该二叉树的hashNext方法和next方法。

调用方法为:

/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = new BSTIterator(root);
 * while (i.hasNext()) v[f()] = i.next();
 */


public class BSTIterator {

   int current = 0;//表示当前要遍历的元素
	int size = 0;//表示二叉查找树中结点总数
	List<Integer> nodeList = new ArrayList<Integer>();
	
	 public BSTIterator(TreeNode root) {
		 if(root != null){
			 nodeList = inorderTraversal(root);
			  size = nodeList.size();
			 //System.out.println("nodeList = "+nodeList);
		 }
	    }

	    /** @return whether we have a next smallest number */
	    public boolean hasNext() {
	        return current < size;
	    }

	    /** @return the next smallest number */
	    public int next() {
	        return nodeList.get(current++);
	    }
	
	    
	    /**
		 * 中序遍历二叉查找树
		 */
		public List<Integer> inorderTraversal(TreeNode root){
			List<Integer> list = new ArrayList<Integer>();
			if(root == null){
				return list;
			}else{
				TreeNode node = root; 
				Stack stack = new Stack();
				stack.push(node);
				/*node表示入栈的元素,popnode表示弹栈的元素*/
				while(!stack.isEmpty()){
					if(node.left != null){
						node = node.left;
						stack.push(node);
					}else{
						TreeNode popnode= (TreeNode) stack.pop();//弹出栈顶元素
						list.add(popnode.val);
						/*如果弹栈的元素有右孩子,则让其右孩子入栈,进行下一次循环*/
						if(popnode.right != null){
							node = popnode.right;
							stack.push(node);
						}
					}
				}
			}
			return list;
		}
}


你可能感兴趣的:(119.Binary Search Tree Iterator)