码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Search Tree Iterator

时间:2016-07-08 06:44:44      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

Design an iterator over a binary search tree with the following rules:

  • Elements are visited in ascending order (i.e. an in-order traversal)
  • next() and hasNext() queries run in O(1) time inaverage.
Example

For the following binary search tree, in-order traversal by using iterator is [1, 6, 10, 11, 12]

   10
 /    1      11
 \         6       12
分析:
把所有的node存在ArrayList,然后用一个指针指向第一个node.
 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  * Example of iterate a tree:
12  * BSTIterator iterator = new BSTIterator(root);
13  * while (iterator.hasNext()) {
14  *    TreeNode node = iterator.next();
15  *    do something for node
16  * } 
17  */
18 public class BSTIterator {
19     //@param root: The root of binary tree.
20     ArrayList<TreeNode> list;
21     int index;
22     public BSTIterator(TreeNode root) {
23         // write your code here
24         list = new ArrayList<TreeNode>();
25         dfs(root, list);
26         
27         index = 0;
28     }
29     
30     public void dfs(TreeNode root, ArrayList<TreeNode> ret) {
31         if (root == null) {
32             return;
33         }
34         
35         //Use inorder traversal.
36         dfs(root.left, ret);
37         ret.add(root);
38         dfs(root.right, ret);
39     }
40 
41     //@return: True if there has next node, or false
42     public boolean hasNext() {
43         return !(index == list.size());
44     }
45     
46     //@return: return next node
47     public TreeNode next() {
48         if (index < list.size()) {
49             return list.get(index++);
50         }
51         return null;
52     }
53 }

 

Binary Search Tree Iterator

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5652082.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!