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

首頁 > 學院 > 開發設計 > 正文

[LeetCode] Binary Search Tree Iterator

2019-11-15 01:08:06
字體:
來源:轉載
供稿:網友
[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.

Callingnext()will return the next smallest number in the BST.

Note:next()andhasNext()should run in average O(1) time and uses O(h) memory, wherehis the height of the tree.

中午下雨了。于是木有吃午飯(=。=)現在有點餓。

這個比較難的就是next() method了,就是喊你返回BTS中最小的那個數。

然后很容易的,我們要先建一個不管是List,stack還是神馬的,反正拿來store每個結點最小的數就行了。(一般情況下就是最左邊的那個數)

當然呢如果最左邊剛好null呢?我們第一次store的時候就肯定會在這里停下了,因此我們需要檢查右邊是否null,如果右邊不是null的,那么就檢查這個右邊的treenode左邊是否null,如果是,繼續接著往下…………

代碼如下。~

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class BSTIterator {    List<TreeNode> tree;    public BSTIterator(TreeNode root) {        tree=new ArrayList<TreeNode>();        while(root!=null){            tree.add(root);            root=root.left;        }            }    /** @return whether we have a next smallest number */    public boolean hasNext() {        return !tree.isEmpty();    }    /** @return the next smallest number */    public int next() {        TreeNode min=tree.remove(tree.size()-1);        TreeNode temp=min.right;        while(temp!=null){            tree.add(temp);            temp=temp.left;        }        return min.val;    }}/** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */


上一篇:[LeetCode] Plus One

下一篇:Java環境編寫

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 长白| 固阳县| 长白| 高陵县| 玉山县| 宜兰市| 桂平市| 罗山县| 文成县| 永新县| 阳江市| 从化市| 无极县| 西丰县| 怀仁县| 莱州市| 建阳市| 丰原市| 纳雍县| 晋中市| 鹰潭市| 武清区| 龙南县| 湘潭市| 汶川县| 遂溪县| 宣武区| 宁强县| 鹤岗市| 普洱| 高邮市| 璧山县| 南澳县| 白玉县| 名山县| 石城县| 岗巴县| 鹤壁市| 西畴县| 多伦县| 荆州市|