刷题-力扣-450. 删除二叉搜索树中的节点

450. 删除二叉搜索树中的节点

题目链接

来源:力扣(LeetCode)
链接:https://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;
    }
};
原文地址:https://www.cnblogs.com/HanYG/p/15203073.html