题目描述
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.
题目大意
给定一个二叉搜索树(BST),基于该搜索树实现两个操作:
next():要求在时间复杂度O(1)内查找树中最小的数值,下次一查找便查找第二小的数值,以此类推。
hasnext():是否还有下次查找的最小值(即是否该二叉查找树已遍历一遍)
示例
E1
BSTIterator iterator = new BSTIterator(root); iterator.next(); // return 3 iterator.next(); // return 7 iterator.hasNext(); // return true iterator.next(); // return 9 iterator.hasNext(); // return true iterator.next(); // return 15 iterator.hasNext(); // return true iterator.next(); // return 20 iterator.hasNext(); // return false
解题思路
Solution1:简单的前序遍历二叉树,用vector一次保存结点数值,在进行操作时可以实现O(1)的复杂度操作。
Solution2:借鉴LeetCode@xcv58的思路,利用一个stack保存当前节点的所有的左孩子结点,每次操作之后将操作结点的右孩子结点保存到stack中,能实现空间复杂度为O(h)(h为树的高度),但查询的操作不为O(1)。
复杂度分析
时间复杂度:O(1O(h))
空间复杂度:O(nO(h))
代码1
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class BSTIterator { public: BSTIterator(TreeNode* root) { init(root); } void init(TreeNode* root) { if(root == NULL) return; init(root->left); node.push_back(root->val); init(root->right); } /** @return the next smallest number */ int next() { int res = node[0]; node.erase(node.begin()); return res; } /** @return whether we have a next smallest number */ bool hasNext() { return (node.size() > 0 ? true : false); } private: vector<int> node; }; /** * Your BSTIterator object will be instantiated and called as such: * BSTIterator* obj = new BSTIterator(root); * int param_1 = obj->next(); * bool param_2 = obj->hasNext(); */
代码2
class BSTIterator { stack<TreeNode *> myStack; public: BSTIterator(TreeNode *root) { pushAll(root); } /** @return whether we have a next smallest number */ bool hasNext() { return !myStack.empty(); } /** @return the next smallest number */ int next() { TreeNode *tmpNode = myStack.top(); myStack.pop(); pushAll(tmpNode->right); return tmpNode->val; } private: void pushAll(TreeNode *node) { for (; node != NULL; myStack.push(node), node = node->left); } };