1. 程式人生 > >LeetCode 第173題 二叉搜索樹叠代器

LeetCode 第173題 二叉搜索樹叠代器

示例 != 內存 pre class 排列 pop 分享 結果

實現一個二叉搜索樹叠代器。你將使用二叉搜索樹的根節點初始化叠代器。

調用 next() 將返回二叉搜索樹中的下一個最小的數。



示例:

技術分享圖片




BSTIterator iterator = new BSTIterator(root);
iterator.next(); // 返回 3
iterator.next(); // 返回 7
iterator.hasNext(); // 返回 true
iterator.next(); // 返回 9
iterator.hasNext(); // 返回 true
iterator.next(); // 返回 15
iterator.hasNext(); // 返回 true

iterator.next(); // 返回 20
iterator.hasNext(); // 返回 false


提示:

next() 和 hasNext() 操作的時間復雜度是 O(1),並使用 O(h) 內存,其中 h 是樹的高度。
你可以假設 next() 調用總是有效的,也就是說,當調用 next() 時,BST 中至少存在一個下一個最小的數。
*/

/**
* Your BSTIterator object will be instantiated and called as such: BSTIterator obj = new
* BSTIterator(root); int param_1 = obj.next(); boolean param_2 = obj.hasNext();

*/


二叉搜索樹中序遍歷:  元素從小到大排列.
如: 技術分享圖片 中序遍歷結果: 3,7,9,15,20



思路1: 隊列式. 中序遍歷二叉樹,將所有節點添加到隊列中.
  空間復雜度=O(n) > O(h)
   next() 時間復雜度O(1)

思路2: 棧式. 利用棧中序遍歷,即通過調用next()來推動遍歷.在沒有調用next()方法時,接下來的元素不一定被訪問到.
   空間復雜度=O(h)
  next() 時間復雜度O(1) **(均攤)**




 1 //隊列式
 2 class BSTIterator_queue {
3 4 private Queue<TreeNode> queue = new ArrayDeque<>(); 5 6 7 public BSTIterator_queue(TreeNode root) { 8 addElem(root); 9 } 10 11 private void addElem(TreeNode root) { 12 if (root != null) { 13 addElem(root.left); 14 queue.add(root); 15 addElem(root.right); 16 } 17 } 18 19 /* 20 * @return the next smallest number 21 */ 22 public int next() { 23 return queue.remove().val; 24 } 25 26 /* 27 * @return whether we have a next smallest number 28 */ 29 public boolean hasNext() { 30 return queue.size() != 0; 31 } 32 33 } 34 35 36 37 ======================================= 38 39 40 41 //棧式 42 class BSTIterator_stack { 43 44 private Stack<TreeNode> stack = new Stack<>(); 45 private TreeNode currNode; 46 47 public BSTIterator_stack(TreeNode root) { 48 currNode = root; 49 } 50 51 /* 52 * @return the next smallest number 53 */ 54 public int next() { 55 while (currNode != null) { 56 stack.push(currNode); 57 currNode = currNode.left; 58 } 59 currNode = stack.pop(); 60 TreeNode tempNode = currNode; 61 currNode = currNode.right; 62 return tempNode.val; 63 } 64 65 /* 66 * @return whether we have a next smallest number 67 */ 68 public boolean hasNext() { 69 return stack.isEmpty() && currNode == null; 70 } 71 }

LeetCode 第173題 二叉搜索樹叠代器