[LeetCode] Binary Search Tree Iterator

來源:互聯網
上載者:User

標籤:

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.

 

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

     這個比較難的就是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] Binary Search Tree Iterator

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.