刷題-力扣-450. 刪除二叉搜索樹中的節點

450. 刪除二叉搜索樹中的節點

題目鏈接

來源:力扣(LeetCode)
鏈接://leetcode-cn.com/problems/delete-node-in-a-bst
著作權歸領扣網路所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

題目描述

給定一個二叉搜索樹的根節點 root 和一個值 key,刪除二叉搜索樹中的 key 對應的節點,並保證二叉搜索樹的性質不變。返回二叉搜索樹(有可能被更新)的根節點的引用。

一般來說,刪除節點可分為兩個步驟:

首先找到需要刪除的節點;
如果找到了,刪除它。
說明: 要求演算法時間複雜度為 O(h),h 為樹的高度。

示例:

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

    5
   / \
  3   6
 / \   \
2   4   7

給定需要刪除的節點值是 3,所以我們首先找到 3 這個節點,然後刪除它。

一個正確的答案是 [5,4,6,2,null,null,7], 如下圖所示。

    5
   / \
  4   6
 /     \
2       7

另一個正確答案是 [5,2,6,null,4,null,7]。

    5
   / \
  2   6
   \   \
    4   7

題目分析

  1. 根據題目描述刪除二叉搜索樹(二叉排序樹)中指定的節點
  2. 利用二叉搜索樹的特性二分查找二叉搜索樹中節點值等於key的節點
  3. 假設刪除的節點為root,若root->right為空則返回root->left;若root->right不空,則讓root->left作為root->right的最左子樹,再返回root->right

程式碼

/**
 * 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 Solution {
public:
    TreeNode* deleteNode(TreeNode* root, int key) {
        if (!root) return nullptr;
        if (root->val == key) {
            if (root->right) {
                TreeNode* p = root->right;
                while (p->left) p = p->left;
                p->left = root->left;
                return root->right;
            } else return root->left;
        } else if (root->val > key) root->left = deleteNode(root->left, key);
        else root->right = deleteNode(root->right, key);
        return root;
    }
};