Leetcode 173バイナリ検索ツリーのイテレータ

免責事項:この記事はブロガーオリジナル記事ですが、許可ブロガーなく再生してはなりません。https://blog.csdn.net/Mr_zhuo_/article/details/88591776

解決策1:

バイナリ検索ツリーが非常に重要な機能:前順で順序付けられたシーケンスです。

あなたは、行きがけのベクトルに格納することができる限り、それぞれがさらに背後にあるいくつかと、次はのhasNextを与えることができるかどうか判断されます

 

コード:

class BSTIterator {
public:
    BSTIterator(TreeNode* root) {
        idx_ = 0;//数组始
        inOrder(root);
        end_ = vec_.size();//数组终
    }
    
    /** @return the next smallest number */
    int next() {
        return vec_[idx_++];
    }
    
    /** @return whether we have a next smallest number */
    bool hasNext() {
        return idx_ != end_;//注意has只是判断,不能更改idx
    }
private:
    void inOrder(TreeNode* root) {
        if (root != nullptr){
            inOrder(root->left);
            vec_.push_back(root->val);
            inOrder(root->right);
        } 
    }
private:
    std::vector<int> vec_;
    int idx_, end_;
};

 

2回答:

再帰は、それぞれ、ツリーのすべての左側の枝を積み重ねることができます(つまり、横断の深さは、最初のリーフノードが停止に遭遇しました)。スタックの現在のトップは、次を尋ねている最小の要素、です。

スタック。ポイント右のノードを入力します。スタックが空になるまで、上記の動作を繰り返します。

ここでの考え方:だけ左連続スタック残します。手動で再帰スタックをシミュレートすることと同じです。スペースの複雑さは、答えよりも低くなっています。

class BSTIterator {
public:
    BSTIterator(TreeNode* root) {
        for (; root != nullptr; root = root->left) {
            sti_.push(root);
        }
    }
    
    /** @return the next smallest number */
    int next() {
        TreeNode* smallest = sti_.top();
        sti_.pop();
        int val = smallest->val;
        smallest = smallest->right;
        for (; smallest != nullptr; smallest = smallest->left) {
            sti_.push(smallest);
        }
        return val;
    }
    
    /** @return whether we have a next smallest number */
    bool hasNext() {
        return !sti_.empty();
    }
private:
    std::stack<TreeNode*> sti_;
};

おすすめ

転載: blog.csdn.net/Mr_zhuo_/article/details/88591776