使用 O(1) 額外記憶體刪除二叉樹

sparkyen發表於2024-09-16

這是一個 naive 的做法:

void deleteTreeRec(TreeNode *root){
   if (root == NULL) return;
   deleteTreeRec(root->left);
   deleteTreeRec(root->right);
   cout << "Deleting node " << root->data << endl;
   delete root;
}

O(1) 空間的做法如下:

把樹的左側節點看成一條鏈,我們的目的就是不斷把當前 root 節點的右子樹挪到這條鏈的末尾,最終可以把這棵樹展平為一條鏈。

而在展開的過程中我們可以刪除這條鏈的頭節點(即root節點),最後可以把這條鏈刪除乾淨。

void deleteTree(TreeNode* root) {
    TreeNode* tail = root;
    while (root != nullptr){
        // update tail
        while (tail->left != nullptr) {
            tail = tail->left;
        }
        // move right to the end of the "list"
        // needs to happen before retrieving next, since the node may only have a right subtree
        tail->left = root->right;
        // need to retrieve the data about the next
        TreeNode* next = root->left;
        delete root;
        root = next;
    }
}

相關文章