1  BST迭代器

注意点:1. 实际就是中序遍历的非递归写法,迭代器就是要用Stack存储数据,不过把不同的模块功能进行了分割,而不是一次完成中序遍历;

    2. 可以把添加到Stack单独抽取成一个函数,面向对象,更容易理解。

http://www.lintcode.com/en/problem/binary-search-tree-iterator/#

 1  public class BSTIterator {
 2     //@param root: The root of binary tree.
 3     TreeNode next = null;
 4     Stack<TreeNode> stack = new Stack<TreeNode>();
 5     public BSTIterator(TreeNode root) {
 6         // write your code here
 7         next = root;
 8     }
 9 
10     //@return: True if there has next node, or false
11     public boolean hasNext() {
12         // write your code here
13         while(next != null) {
14             stack.push(next);
15             next = next.left;
16         }
17         if(stack.isEmpty()) return false;
18         return true;
19     }
20     
21     //@return: return next node
22     public TreeNode next() {
23         // write your code here
24         if(!hasNext()) return null;
25         TreeNode cur = stack.pop();
26         if(cur.right == null) next = null;
27         else next = cur.right;
28         return cur;
29     }
30 }
View Code

相关文章:

  • 2022-12-23
  • 2021-09-05
  • 2021-04-02
  • 2021-07-12
  • 2022-01-02
  • 2021-11-13
  • 2021-07-18
  • 2021-08-05
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-07-08
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-01
相关资源
相似解决方案