Leetcode Binary Search Tree Iterator

来源:互联网 发布:试题软件 编辑:程序博客网 时间:2024/05/29 16:28

题意:写一个二叉搜索树的迭代器。

思路:中序遍历。

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class BSTIterator {public:    BSTIterator(TreeNode *root) {        dfs(root);        n = 0;    }    /** @return whether we have a next smallest number */    bool hasNext() {        return n < re.size();    }    /** @return the next smallest number */    int next() {        return re[n ++];    }        vector<int> re;    int n;    void dfs(TreeNode* root) {        if(root == NULL) return;                dfs(root->left);        re.push_back(root->val);        dfs(root->right);                return;    }};/** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */

这样的方法虽然实现了O(1)的时间复杂度,但是没有达到O(h)的空间复杂度。可以用堆栈实现O(h)的空间复杂度,但时间复杂度变为O(h)。

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class BSTIterator {public:    BSTIterator(TreeNode *root) {        dfs(root);    }    /** @return whether we have a next smallest number */    bool hasNext() {        return !mys.empty();    }    /** @return the next smallest number */    int next() {        TreeNode* temp = mys.top();        mys.pop();        dfs(temp->right);                return temp->val;    }        stack<TreeNode*> mys;    void dfs(TreeNode* root) {        while(root) {            mys.push(root);            root = root->left;        }        return;    }};/** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */


0 0