【发布时间】:2016-11-11 16:30:10
【问题描述】:
我正在研究一种从 BST 中删除节点的方法。在相同的方法中,我递归地搜索要删除的节点以及保存该节点的父节点。但是,唯一的问题是我不确定在case2中如何使根节点等于父节点(因为删除发生在父节点中)。
public Node delete(Node root, int data)
{
// base case - if tree is empty
if (root == null)
return root;
// find the node to be deleted and keep track of parent
if (data < root.data)
{
parent = root;
System.out.println("parent node: " + parent.data);
root.left = delete(root.left, data);
}
else if (data > root.data)
{
parent = root;
System.out.println("parent node: " + parent.data);
root.right = delete(root.right, data);
// delete node
}
else
{
// case 1: deletion node has no subtrees
if (root.left == null && root.right == null)
{
System.out.println(data + " successfully deleted from tree (case1)");
root = null;
}
// case 2: deletion node has only one subtree
else if (root.left != null && root.right == null)
{
Node temp = root.left;
if(parent.left.data == root.left.data)
{
parent.left = null;
System.out.println(data + " successfully deleted from tree (case2)");
parent.left = temp;
root = parent; // parent was sent when searching for the node
}
else if(parent.right.data == root.data)
{
parent.right = null;
System.out.println(data + " successfully deleted from tree (case2)");
parent.left = temp;
root = parent; // parent was sent when searching for the node
}
}
else if (root.left == null && root.right != null)
{
// same logic
}
}
return root;
}
【问题讨论】: