Try   HackMD

173. Binary Search Tree Iterator

  • 設計一個能夠迭代訪問 BST 所有節點的迭代器,並且以中序走訪的順序(從小到大)返回節點的值。
  • inorder: left -> root -> right。
  • 使用 stack
  • 初始化的時候,將左子樹的節點都推到 stack
  • next() 方法從 stack.top() 彈出節點,然後處理其右子樹(如果有),然後將右子樹的所有左子節點再次推入 stack 中。
Solution
/** * 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: stack<TreeNode*> stk; public: BSTIterator(TreeNode* root) { while (root) { // 探索左邊的樹 stk.push(root); root = root->left; } } int next() { TreeNode* node = stk.top(); stk.pop(); // 回傳 node_val 的值 int node_val = node->val; // 如果有右子樹的話,探索右邊的樹 if (node->right) { // 指標到下一個節點 node = node->right; // 如果 node 存在的話 while (node) { // 將右子樹的所有左子節點再次推入 stack 中。 stk.push(node); node = node->left; } } return node_val; } bool hasNext() { return !stk.empty(); } }; /** * 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(); */
  • 時間複雜度:
    O()
  • 空間複雜度:
    O()