[leetcode] 173. Binary Search Tree Iterator

来源:互联网 发布:声音好听的网络男歌手 编辑:程序博客网 时间:2024/06/07 02:09

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.


这道题是实现BST迭代器,题目难度为Medium。


BST相信大家都熟悉,就不详细介绍了。根据BST的特点,中序遍历BST即得到节点值从小到大排列的所有节点。next()函数找下一个最小值节点,即中序遍历的下一节点,从根节点开始,一直向左子树遍历,直到遍历到左子树为空的节点为止,此时的节点即是初始的最小值节点遍历此节点,之后跳转到它的右子树(如果不为空)继续遍历,在遍历完右子树之后,以此节点为根的子树就遍历完了,此时要跳转到它的父节点继续遍历,所以这里需要借助栈来存储遍历路径上的所有节点以便回退时使用,即中序遍历二叉树的思路。


题目限定时间复杂度O(1),空间复杂度O(h),所以构造函数要将栈中数据预先准备好,以便next()函数返回栈顶元素;hasNext()函数判断栈是否为空即可;next()函数在出栈返回最小值之后,要跳转到最小值节点的右子树继续中序遍历的相应操作。具体代码:

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class BSTIterator {    stack<TreeNode*> stk;public:    BSTIterator(TreeNode *root) {        while(root) {            stk.push(root);            root = root->left;        }    }    /** @return whether we have a next smallest number */    bool hasNext() {        return !stk.empty();    }    /** @return the next smallest number */    int next() {        TreeNode* n = stk.top();        int ret = n->val;        stk.pop();        n = n->right;        while(n) {            stk.push(n);            n = n->left;        }        return ret;    }};/** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */
空间复杂度O(h)达到了,hasNext()函数的时间复杂度O(1)也达到了,next()函数至多调用节点个数次,而栈的入栈和出栈最多也是节点个数次,所以next()函数的平均时间复杂度也是O(1)。

0 0
原创粉丝点击