[LeetCode] 173. Binary Search Tree Iterator Java

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.