1. 程式人生 > >[leetcode] 450. Delete Node in a BST 解題報告

[leetcode] 450. Delete Node in a BST 解題報告

題目連結: https://leetcode.com/problems/delete-node-in-a-bst/

Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.

Basically, the deletion can be divided into two stages:

  1. Search for a node to remove.
  2. If the node is found, delete the node.

Note: Time complexity should be O(height of tree).

Example:

root = [5,3,6,2,4,null,7]
key = 3

    5
   / \
  3   6
 / \   \
2   4   7

Given key to delete is 3. So we find the node with value 3 and delete it.

One valid answer is [5,4,6,2,null,null,7], shown in the following BST.

    5
   / \
  4   6
 /     \
2       7

Another valid answer is [5,2,6,null,4,null,7].

    5
   / \
  2   6
   \   \
    4   7

思路: 剛開始考慮用迭代來做, 發現非常麻煩, 因為使用迭代的話刪除那個節點之後還需要重新連線其父節點指標, 也就是需要記錄父節點. 這樣的話就變得很麻煩, 因為還有一些特殊的情況, 比如要刪除的節點是根節點, 或者還需要記錄當前節點是父節點的左子樹還是右子樹. 

在此時遞迴就體現了其優越性, 因為遞迴是可以回溯的, 所以不需要記錄父節點. 然後考慮刪除以後節點的替換. 有四種替換方式:

1. 如果要刪除的節點有左孩子, 則可以直接讓左孩子替換其位置, 並且讓左孩子的右子樹連線到要刪除節點的右孩子的最左端

2. 如果要刪除的節點有右孩子, 則可以讓右孩子替換其位置, 並且讓右孩子的左子樹連線到要刪除節點的左孩子的最右端

3. 如果要刪除的節點有左孩子, 則可以取左孩子的最右節點替換要刪除的節點

4. 如果要刪除的節點有右孩子, 則可以去右孩子的最左節點替換要刪除的節點.

在這裡我採用的第二種解法.

程式碼如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* deleteNode(TreeNode* root, int key) {
        if(!root) return root;
        if(root->val > key){
            root->left = deleteNode(root->left, key);
            return root;
        }
        else if(root->val < key){
            root->right = deleteNode(root->right, key);
            return root;
        }
        TreeNode* left = root->left, *right = root->right, *tem = left;
        delete root;
        if(!left || !right) return left?left: right;
        while(tem->right) tem = tem->right;
        tem->right = right->left, right->left = left;
        return right;
    }
};