Binary Search Tree Iterator

来源:互联网 发布:电影网站源码带采集 编辑:程序博客网 时间:2024/05/01 18:32

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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

这题首先要弄明白一点。

一颗BST,它的最小值是哪个点?没错,就是这颗树的最左一个节点。那么它之后的最小节点呢?

就变成了找比当前节点大的最小的那个节点。就是当前节点右子树中最左的那个节点、如果右子树不存在,那么是其父节点

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


0 0
原创粉丝点击