Remove Node in Binary Search Tree
Description
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.
/**
* 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) {
// write your code here
TreeNode dummy = new TreeNode(0) ;
dummy.left = root ;
//find parent and target
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 ;
}
}
/*if (root == null){
return null ;
}
if(root.left == null && root.right == null && root.val == value){
root = null ;
return root;
}
if(root.left == null && root.right != null && root.val == value){
root = root.right ;
return root;
}
if(root.left != null && root.right == null && root.val == value){
root = root.left ;
return root;
}
if (root.val == value ){
TreeNode temp = root.right ;
root = root.left;
root.right = temp ;
// root.left = root.left.left ;
}
if(value < root.val){
root.left = removeNode(root.left , value);
}else{
root.right = removeNode(root.right , value);
}
return root ;*/
}
这个博客讨论了如何在保持二叉搜索树性质不变的情况下删除具有唯一值的节点。提供了一个名为`Solution`的类,包含`removeNode`方法来删除具有给定值的节点。该方法首先找到目标节点及其父节点,然后根据节点的位置进行删除操作。此外,还包含辅助方法`findNode`用于查找节点和`deleteNode`用于实际删除操作。
317

被折叠的 条评论
为什么被折叠?



