第一部是先递归遍历找到key == root->val;
删除一个节点有以下情况:
1,node->right == NULL node->left == NULL
直接删除
2,node->right 或者node->left其中一个非NULL,另外一个是NULL
直接返回子孩子得地址
3,node->left != NULL && node->right !=NULL
从右子树里面挑选出最小的来替换掉当前节点,(右子树最左边的节点),因为这个节点可以满足大于所有的左树和小于所有的右树
/* Given a binary search tree and a key, this function deletes the key
and returns the new root */
struct TreeNode* deleteNode(struct TreeNode* root, int key)
{
// base case
if (root == NULL) return root;
// If the key to be deleted is smaller than the root's key,
// then it lies in left subtree
if (key < root->val)
root->left = deleteNode(root->left, key);
// If the key to be deleted is greater than the root's key,
// then it lies in right subtree
else if (key > root->val)
root->right = deleteNode(root->right, key);
// if key is same as root's key, then This is the node
// to be deleted
else
{
// node with only one child or no child
if (root->left == NULL)
{
struct TreeNode *temp = root->right;
free(root);
return temp;
}
else if (root->right == NULL)
{
struct TreeNode *temp = root->left;
free(root);
return temp;
}
// node with two children: Get the inorder successor (smallest
// in the right subtree)
struct TreeNode *temp ;
temp = root->right;
while(temp->left)
temp = temp->left;
// Copy the inorder successor's content to this node
root->val = temp->val;
// Delete the inorder successor
root->right = deleteNode(root->right, temp->val);
}
return root;
}