简单思路:参考下面给出的代码,如果删除的节点没有左右节点,直接删除;如果只有左节点,左节点赋值给准备删除的节点;如果只有右节点,右节点赋值给准备删除的节点;如果左右节点都有,我们找出要删除的节点的所有右节点中的最小值赋值给要删除的节点,并且把这个最小的节点删掉,或者找出要删除的所有左节点中的最大值赋值给要删除的节点,并把这个最大的节点删除,大功告成
如果删除的节点有左右两个节点,有两种方式
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
36
37
38
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {number} key
* @return {TreeNode}
*/
var deleteNode = function (root, key) {
if (!root) return root;
if (root.val > key) {
root.left = deleteNode(root.left, key);
} else if (root.val < key) {
root.right = deleteNode(root.right, key);
} else {
if (root.left === null && root.right === null) {
root = null;
} else if (root.left !== null && root.right === null) {
root = root.left;
} else if (root.right !== null && root.left === null) {
root = root.right;
} else if (root.left !== null && root.right !== null) {
let last = root.right;
while (last && last.left) {
last = last.left;
}
root.val = last.val;
root.right = deleteNode(root.right, last.val);
}
}
return root;
};
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
36
37
38
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {number} key
* @return {TreeNode}
*/
var deleteNode = function (root, key) {
if (!root) return root;
if (root.val > key) {
root.left = deleteNode(root.left, key);
} else if (root.val < key) {
root.right = deleteNode(root.right, key);
} else {
if (root.left === null && root.right === null) {
root = null;
} else if (root.left !== null && root.right === null) {
root = root.left;
} else if (root.right !== null && root.left === null) {
root = root.right;
} else if (root.left !== null && root.right !== null) {
let last = root.left;
while (last && last.right) {
last = last.right;
}
root.val = last.val;
root.left = deleteNode(root.left, last.val);
}
}
return root;
};