国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發(fā)設計 > 正文

Leetcode: Binary Search Tree Iterator

2019-11-14 22:44:07
字體:
來源:轉載
供稿:網(wǎng)友
Leetcode: Binary Search Tree Iterator
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.

其實這道題的方法就是用迭代來中序遍歷BST,用一個棧來模擬。為什么用迭代,因為迭代才可以這樣一步一步地輸出next元素,遞歸都是一口氣輸出完。

迭代用stack,棧的最大高度就是樹的高度。

我對這道題唯一有疑問的地方在于next()的average時間復雜度要是O(1),這里average值得推敲,因為不是每次next()時間復雜度都是O(1)的。

因為一個node pop()之后,需要把它右子樹node入棧,不僅如此,還需要沿著右子樹node的左子樹一路push下去,直到這一路全部入棧。這樣做我不確定時間復雜度是O(1), 因為worst case時間復雜度可以到O(N). 比如:

1

/

2

/

3

/

4

1節(jié)點pop()了之后,需要把2、3、4節(jié)點依次入棧,該次復雜度達到了O(N)。但是轉念想想,4、3、2出棧的時候時間復雜度都是O(1),所以average的情況可以算是O(1)吧,值得推敲。一般不是這么極端的例子,1節(jié)點右子樹節(jié)點2的左節(jié)點這一路應該是常數(shù)個節(jié)點,所以average入棧時間應該是O(1)

 1 /** 2  * Definition for binary tree 3  * public class TreeNode { 4  *     int val; 5  *     TreeNode left; 6  *     TreeNode right; 7  *     TreeNode(int x) { val = x; } 8  * } 9  */10 11 public class BSTIterator {12     Stack<TreeNode> st;13 14     public BSTIterator(TreeNode root) {15         st = new Stack<TreeNode>();16         pushLeft(root);17     }18     19     public void pushLeft(TreeNode root) {20         while (root != null) {21             st.push(root);22             root = root.left;23         }24     }25 26     /** @return whether we have a next smallest number */27     public boolean hasNext() {28         return !st.isEmpty();29     }30 31     /** @return the next smallest number */32     public int next() {33         TreeNode current = st.pop();34         pushLeft(current.right);35         return current.val;36     }37 }38 39 /**40  * Your BSTIterator will be called like this:41  * BSTIterator i = new BSTIterator(root);42  * while (i.hasNext()) v[f()] = i.next();43  */


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 弥勒县| 惠州市| 阳西县| 石首市| 都匀市| 扬中市| 黑龙江省| 高唐县| 鱼台县| 当阳市| 丽水市| 花莲县| 峨边| 肇东市| 京山县| 小金县| 蒙自县| 留坝县| 璧山县| 铜川市| 龙里县| 双鸭山市| 句容市| 射阳县| 开鲁县| 灵丘县| 万荣县| 城口县| 苗栗市| 嵊泗县| 雅江县| 五家渠市| 台中县| 磐石市| 苏州市| 乐至县| 林周县| 合山市| 虎林市| 青田县| 浦北县|