标签:
Design an iterator over a binary search tree with the following rules:
next()
and hasNext()
queries run in O(1) time inaverage.For the following binary search tree, in-order traversal by using iterator is [1, 6, 10, 11, 12]
10
/ 1 11
\ 6 12
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 }
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5652082.html