Every day a Leetcode
題目來源:173. 二叉搜索樹迭代器
解法1:中序遍歷
我們可以直接對二叉搜索樹做一次完全的遞歸遍歷,獲取中序遍歷的全部結果并保存在數組中。隨后,我們利用得到的數組本身來實現迭代器。
代碼:
/** @lc app=leetcode.cn id=173 lang=cpp** [173] 二叉搜索樹迭代器*/// @lc code=start
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode() : val(0), left(nullptr), right(nullptr) {}* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}* };*/
class BSTIterator
{
private:int index = 0;vector<int> nums;// 輔函數void inOrder(TreeNode *root, vector<int> &nums){if (root == nullptr)return;inOrder(root->left, nums);nums.push_back(root->val);inOrder(root->right, nums);}// 中序遍歷vector<int> inOrderTraversal(TreeNode *root){vector<int> res;inOrder(root, res);return res;}public:BSTIterator(TreeNode *root) : index(0), nums(inOrderTraversal(root)){}int next(){int num = nums[index];index++;return num;}bool hasNext(){return (index < nums.size());}
};/*** 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();*/
// @lc code=end
結果:
復雜度分析:
時間復雜度:初始化需要 O(n) 的時間,其中 n 為樹中節點的數量。隨后每次調用只需要 O(1) 的時間。
空間復雜度:O(n),因為需要保存中序遍歷的全部結果。
解法2:迭代
除了遞歸的方法外,我們還可以利用棧這一數據結構,通過迭代的方式對二叉樹做中序遍歷。此時,我們無需預先計算出中序遍歷的全部結果,只需要實時維護當前棧的情況即可。
代碼:
class BSTIterator {
private:TreeNode* cur;stack<TreeNode*> stk;
public:BSTIterator(TreeNode* root): cur(root) {}int next() {while (cur != nullptr) {stk.push(cur);cur = cur->left;}cur = stk.top();stk.pop();int ret = cur->val;cur = cur->right;return ret;}bool hasNext() {return cur != nullptr || !stk.empty();}
};
結果:
復雜度分析: