[Binary search tree] leetcode450: Delete binary search tree node (medium)

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_43152052/article/details/100168561

topic:
Here Insert Picture Description

Solution:
traversing the binary sort tree to find the node you want to delete, then 判断该删除节点的左子树是否为空. If not empty, then traverse left subtree find 该左子树的最右边节点, that is, the left sub-tree node value of the maximum points, then we will be 删除节点的右子树连接on the rightmost node in the left subtree, and finally weConnected on the deleted node右子树的左子树的根节点To cover 需要删除的节点. If it is empty, then we directly use 右子树的根节点to cover 需要删除的节点.

code show as below:

class Solution {
public:
    TreeNode* deleteNode(TreeNode* root, int key) {
        if(root==nullptr)return nullptr;
        if (root->val == key) //找到需要删除的节点
        {
            if (root->left)
            {//遍历删除节点的左子树,找到该左子树的最右边节点,也就是整个左子树中的最大值,然后将删除的节点的右子树连接到最右边节点上,返回左子树
                TreeNode* node = root->left;
                while (node->right) node = node->right;
                node->right = root->right;
                return root->left;
            }
            //左子树为空,直接将右子树节点替换到删除节点上
            return root->right;
        }
        if (root->val > key)
            root->left = deleteNode(root->left, key);
        else
            root->right = deleteNode(root->right, key);
        return root;
    }
};

Another approach:
with a question on the same idea, just delete nodes left sub-tree node is connected to the left and right subtree delete nodes, that is, the minimum value of the right child node of the tree. (Root left subtree is the left subtree of a node the maximum value but still less than the right subtree of a node minimum value).

class Solution {
public:
    TreeNode* deleteNode(TreeNode* root,int key)
    {
        if(root==nullptr)return nullptr;
        if(root->val==key)
        {
            if(root->right)
            {//遍历删除节点的右子树,找到该右子树的最左边节点,也就是整个右子树中的最小值,然后将删除节点的左子树连接到最左边节点上,返回右子树
             //因为删除节点左子树的所有节点都小于删除节点,而删除节点的右子树的所有节点都大于删除节点,所以右子树中的最小节点值也会大于左子树中的最大节点值
             	TreeNode* node=root->right;
                while(node->left)node=node->left;
                node->left=root->left;
                return root->right;
            }
            //若右子树为空,直接将删除节点的左子树
            return root->left;
        }
        if (root->val > key)
            root->left = deleteNode(root->left, key);
        else
            root->right = deleteNode(root->right, key);
        return root;
    }
};

Guess you like

Origin blog.csdn.net/qq_43152052/article/details/100168561