標籤:and 二叉樹的遍曆 時間 div run 時間複雜度 判斷 blog 遍曆
題目:
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling next() will return the next smallest number in the BST.
Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
題意及分析:給出一個二叉排序樹,求一個該二叉樹的遍曆器,滿足:(1)hasNext()判斷樹中是否存在一個除了當前數的最小數。 (2)next()返回樹中除了當前數的最小數。(3)要求o(1)的時間複雜度和o(h)的空間複雜度。使用一個棧儲存即可,初始儲存從根節點到最左節點的值,對於next,如果stack非空就存在hasnext smallest number;對於next,下一個最小的就是棧頂的值(因為該棧頂點的左子節點就是當前點,而棧頂點的右子樹上的點肯定比棧頂點大),取出棧頂的點,然後對該點的右子節點左上面的操作(即遍曆該點到該點的最左分葉節點)。
代碼:
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class BSTIterator { private Stack<TreeNode> stack; public BSTIterator(TreeNode root) { stack = new Stack<>(); TreeNode cur = root; while(cur != null){ stack.push(cur); if(cur.left != null) cur = cur.left; else break; } } /** @return whether we have a next smallest number */ public boolean hasNext() { return !stack.isEmpty(); } /** @return the next smallest number */ public int next() { TreeNode node = stack.pop(); TreeNode cur = node; // traversal right branch if(cur.right != null){ cur = cur.right; while(cur != null){ stack.push(cur); if(cur.left != null) cur = cur.left; else break; } } return node.val; }}/** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */
[LeetCode] 173. Binary Search Tree Iterator Java