删除二叉搜索树中的节点。题意是给一个二叉搜索树和一个节点key,请将key从BST中删除并维持BST的性质。例子,
Example:
root = [5,3,6,2,4,null,7] key = 3 5 / \ 3 6 / \ \ 2 4 7 Given key to delete is 3. So we find the node with value 3 and delete it. One valid answer is [5,4,6,2,null,null,7], shown in the following BST. 5 / \ 4 6 / \ 2 7 Another valid answer is [5,2,6,null,4,null,7]. 5 / \ 2 6 \ \ 4 7
因为是BST所以查找要删除的节点应该很简单,如果比root小就往左走,比root大就往右走。难点在于删除了节点之后如何维持剩下的节点依然是一个BST。分如下几种情况,
1. 如果要删除的节点没有左子树,则直接用这个节点的右孩子顶上来;
2. 如果要删除的节点没有右子树,则直接用这个节点的左孩子顶上来;
3. 如果要删除的节点有左右子树,需要去右子树里面找出最小的节点顶上来,这个节点是右子树里面最小的左孩子。(参见代码中的findMin函数)找到这个最小的左孩子,替换掉key之后,记得需要把这个节点删去,因为这个节点出现了两次。
时间O(h) - 题目要求
空间O(h) - 题目要求
Java实现
1 class Solution {
2 public TreeNode deleteNode(TreeNode root, int key) {
3 // corner case
4 if (root == null)
5 return null;
6
7 // normal case
8 if (key < root.val) {
9 root.left = deleteNode(root.left, key);
10 } else if (key > root.val) {
11 root.right = deleteNode(root.right, key);
12 } else {
13 if (root.left == null) {
14 return root.right;
15 } else if (root.right == null) {
16 return root.left;
17 }
18 TreeNode minNode = findMin(root.right);
19 root.val = minNode.val;
20 root.right = deleteNode(root.right, root.val);
21 }
22 return root;
23 }
24
25 private TreeNode findMin(TreeNode node) {
26 while (node.left != null) {
27 node = node.left;
28 }
29 return node;
30 }
31 }
JavaScript实现
1 /**
2 * @param {TreeNode} root
3 * @param {number} key
4 * @return {TreeNode}
5 */
6 var deleteNode = function (root, key) {
7 // corner case
8 if (root == null) {
9 return null;
10 }
11
12 // normal case
13 if (key < root.val) {
14 root.left = deleteNode(root.left, key);
15 } else if (key > root.val) {
16 root.right = deleteNode(root.right, key);
17 } else {
18 if (root.left == null) {
19 return root.right;
20 } else if (root.right == null) {
21 return root.left;
22 }
23 let minNode = findMin(root.right);
24 root.val = minNode.val;
25 root.right = deleteNode(root.right, root.val);
26 }
27 return root;
28 };
29
30 var findMin = function (node) {
31 while (node.left !== null) {
32 node = node.left;
33 }
34 return node;
35 };
来源:https://www.cnblogs.com/aaronliu1991/p/12466922.html