Remove Node in Binary Search Tree
今天是一道题目,来自LintCode,难度为Hard,Acceptance为25%。
题目如下
Given a root of Binary Search Tree with unique value for each node. Remove the node with given value. If there is no such a node with given value in the binary search tree, do nothing. You should keep the tree still a binary search tree after removal.
Example
Given binary search tree:
5
/ \
3 6
/ \
2 4
Remove 3, you can either return:
5
/ \
2 6
\
4
or :
5
/ \
4 6
/
2
解题思路及代码见阅读原文
回复0000查看更多题目
解题思路
首先,该题在《算法导论》一书中是有的。思路也较为容易理解,关键是实现算法时需要注意的各种细节。
那么下面说明该题的思路:
第一步,当然是找到要删除的节点node
和它的父节点parent
,这里采用前序遍历即可。如题目中所说,如果找到了就继续,否则什么都不做,直接返回。
第二步,就是删除该node
节点,这里分为两种情况:
-
node
节点的右子树不存在。此时,直接用parent
节点的子节点指向该node
节点的左节点。 -
node
节点的右子树存在。此时,需要找到右子树的最小节点,用该节点替换node
节点。
技巧:
因为要删除的节点可能是根节点,因此为了算法的通用性,可以首先new一个dummy
节点,该节点的左节点指向根节点,这样处理起来更为方便。
最后,我们来看代码。
代码如下
Java版
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of the binary search tree.
* @param value: Remove the node with given value.
* @return: The root of the binary search tree after removal.
*/
public TreeNode removeNode(TreeNode root, int value) {
TreeNode dummy = new TreeNode(0);
dummy.left = root;
TreeNode parent = findNode(dummy, root, value);
TreeNode node;
if (parent.left != null && parent.left.val == value) {
node = parent.left;
} else if (parent.right != null && parent.right.val == value) {
node = parent.right;
} else {
return dummy.left;
}
deleteNode(parent, node);
return dummy.left;
}
private TreeNode findNode(TreeNode parent, TreeNode node, int value) {
if (node == null) {
return parent;
}
if (node.val == value) {
return parent;
}
if (value < node.val) {
return findNode(node, node.left, value);
} else {
return findNode(node, node.right, value);
}
}
private void deleteNode(TreeNode parent, TreeNode node) {
if (node.right == null) {
if (parent.left == node) {
parent.left = node.left;
} else {
parent.right = node.left;
}
} else {
TreeNode temp = node.right;
TreeNode father = node;
while (temp.left != null) {
father = temp;
temp = temp.left;
}
if (father.left == temp) {
father.left = temp.right;
} else {
father.right = temp.right;
}
if (parent.left == node) {
parent.left = temp;
} else {
parent.right = temp;
}
temp.left = node.left;
temp.right = node.right;
}
}
}
网友评论