Leetcode 173.二叉搜索树迭代器

二叉搜索树迭代器

实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。

调用 next() 将返回二叉搜索树中的下一个最小的数。

注意:next() 和hasNext() 操作的时间复杂度是O(1),并使用 O(h) 内存,其中 是树的高度。

维护一个栈,先将根结点的左子树全部压栈,每次弹出栈顶元素,若某次弹出的栈顶元素有右子树,比如3,此时需要将以该节点的右子树为根的子树的左子节点全部压栈

 

 1 public class BSTIterator{
 2     Stack<TreeNode> stack=new Stack<TreeNode>();
 3     public BSTIterator(TreeNode root){
 4         while(root!=null){
 5             stack.push(root);
 6             root=root.left;
 7         }
 8     }
 9 
10     public boolean hasNext(){
11         return !stack.isEmpty();
12     }
13 
14     public int next(){
15         TreeNode minCurrent=stack.pop();
16         if(minCurrent.right!=null){
17             TreeNode rightNode=minCurrent.right;
18             while(rightNode!=null){
19                 stack.push(rightNode);
20                 rightNode=rightNode.left;
21             }
22         }
23         return minCurrent.val;
24     }
25 }

 

 

原文地址:https://www.cnblogs.com/kexinxin/p/10202986.html