? leetcode 173. Binary Search Tree Iterator 設計迭代器(搜尋樹)--------- java

來源:互聯網
上載者:User

標籤:sea   高效   array   led   空間   ret   discuss   discus   else   

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()與hasNext()是平均O(1)的時間複雜度,O(h)的空間複雜度,h是樹高。

 

1、用棧來實現,棧中儲存的是當前路徑的左孩子。

 

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class BSTIterator {    Stack<TreeNode> stack;    public BSTIterator(TreeNode root) {        stack = new Stack();        if (root == null){            return ;        }        while (root != null){            stack.push(root);            root = root.left;        }    }    /** @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();        int ans = node.val;        if (node.right != null){            node = node.right;            while (node != null){                stack.push(node);                node = node.left;            }        }        return ans;    }        }/** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */

 

 

2、用list實現。直接排序然後儲存在list中,代碼簡單高效。(參考discuss)。

這種方法雖然比上面的方法快並且簡單,但是使用的空間是O(N)的空間,比上一個多,如果上一個題意中說明該設計類只能用O(h)的空間,那麼這種解法就不對了。

ArrayDeque<Integer> list;public BSTIterator(TreeNode root) {    list = new ArrayDeque<Integer>();    inorderTraverse(root);}void inorderTraverse(TreeNode root){    if(root == null)        return;    inorderTraverse(root.left);    list.addLast(root.val);    inorderTraverse(root.right);}/** @return whether we have a next smallest number */public boolean hasNext() {    if(list.isEmpty())        return false;    else        return true;}/** @return the next smallest number */public int next() {    return list.removeFirst();}

 

? 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.