解题思路

只需要分类讨论就行,根据不同情况进行不同的处理

  1. 节点为空:return root
  2. 节点==val:
    1. 左右不为空:将要删除的节点的左树连接到右树的最左节点的左
    2. 左为空,右不为空:return root.right
    3. 左不为空,右为空:return root.left
  3. 节点>val:说明val在当前节点的左子树中
  4. 节点<val:说明val在当前节点的右子树中

代码

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
if root is None: return root
if root.val == key:
if root.left and root.right:
cur = root.right
# 找到右孩子的最左叶子节点
while cur.left:
cur = cur.left
cur.left = root.left
return root.right
elif not root.right: return root.left
elif not root.left: return root.right
else: return None
if root.val > key: root.left = self.deleteNode(root.left, key)
if root.val < key: root.right = self.deleteNode(root.right, key)
return root

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* 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 == NULL) return root;
if (root->val == key) {
if (root->left == NULL) return root->right;
else if (root->right == NULL) return root->left;
else {
TreeNode* cur = root->right;
while (cur->left != NULL) {
cur = cur->left;
}
cur->left = root->left;
TreeNode* tmp = root;
root = root->right;
delete tmp;
return root;
}
}
else if (root->val > key) root->left = deleteNode(root->left, key);
else if (root->val < key) root->right = deleteNode(root->right, key);
return root;
}
};

Go

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func deleteNode(root *TreeNode, key int) *TreeNode {
    if (root == nil) {return root}
    if (root.Val == key) {
        if (root.Left != nil && root.Right != nil) {
            cur := root.Right
            for cur.Left != nil {
                cur = cur.Left
            }
            cur.Left = root.Left
            return root.Right
        } else if (root.Left == nil) {
            return root.Right
        } else if (root.Right == nil) {
            return root.Left
        }
    } else if (root.Val > key) {
        root.Left = deleteNode(root.Left, key)
    } else if (root.Val < key) {
        root.Right = deleteNode(root.Right, key)
    }
    return root

}