LeetCode173. 二叉搜尋樹迭代器
阿新 • • 發佈:2018-12-12
實現一個二叉搜尋樹迭代器。你將使用二叉搜尋樹的根節點初始化迭代器。
呼叫 next()
將返回二叉搜尋樹中的下一個最小的數。
注意:next()
和hasNext()
操作的時間複雜度是O(1),並使用 O(h) 記憶體,其中 h 是樹的高度。
思路:因為BST後續遍歷的結果為從大到小的排序,因此定義一個棧結構stack來儲存BST後序遍歷的結果,當取出棧頂元素時始終為最小元素。
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class BSTIterator { private ArrayDeque<Integer> stack=new ArrayDeque<Integer>();//用來儲存二叉搜尋樹的深度優先遍歷結果結點值 public BSTIterator(TreeNode root) { dfs(root,stack);//將深度優先遍歷BST的結果存入stack } /** @return whether we have a next smallest number */ public boolean hasNext() { if(!stack.isEmpty()) return true; return false; } /** @return the next smallest number */ public int next() { return stack.pop(); } public void dfs(TreeNode root,ArrayDeque<Integer> stack){ if(root==null){ return ; } if(root.right!=null){ dfs(root.right,stack); } // System.out.println(root.val); stack.push(root.val); if(root.left!=null){ dfs(root.left,stack); } } } /** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */