这是我数据结构课程中的一项作业,我的教授希望我创建一个remove方法,该方法基于整数键从树中删除节点。如果找不到该键,则该功能不应执行任何操作。我发现的所有示例的树都基于父节点,左节点和右节点。该程序只有一个左右节点。我试图包括尽可能多的与我相关的课程。几乎只省略了打印树木的方法。
public class BinarySearchTree
{
private Node root;
public BinarySearchTree() { this.root = null; }
public BinarySearchTree ( Node root ) { this.root = root; }
public void add ( Integer key, String value )
{
if (root == null)
root = new Node( key, value);
else
root.add( key, value);
}
public boolean contains ( Integer key )
{
return root == null ? null : ( boolean ) root.contains( key );
}
public void remove ( Integer key )
{
}
}
public class Node
{
public Node left;
public Node right;
public Integer key;
public String value;
public Node (String value, Node left, Node right)
{
this.value = value;
this.left = left;
this.right = right;
}
public Node (String value)
{
this.value = value;
this.left = null;
this.right = null;
}
public Node (Integer key, String value)
{
this.key = key;
this.value = value;
}
public void add ( Integer key, String value )
{
if ( key.compareTo ( this.key ) < 0)
{
if ( left != null )
left.add ( key, value );
else
left = new Node ( key, value );
}
else if ( key.compareTo ( this.key ) > 0 )
{
if ( right != null )
right.add ( key, value );
else
right = new Node ( key, value);
}
else
this.value = value;
}
public Serializable contains ( Integer key )
{
if ( this.key == ( key ) )
return value;
if ( key.compareTo ( this.key ) < 0 )
return left == null ? null : left.contains ( key );
else
return right == null ? null : right.contains ( key );
}
public void remove ( Integer key )
{
}
}
答案 0 :(得分:0)
在这里,remove()
没有Node
类具有parent
。
Node remove(Node root, int key) {
if (root == null) return root;
if (key < root.key)
root.left = remove(root.left, key);
else if (key > root.key)
root.right = remove(root.right, key);
else {
// node with only one child or no child
if (root.left == null)
return root.right;
else if (root.right == null)
return root.left;
// node with two children: Get the inorder successor (smallest
// in the right subtree)
root.key = minValue(root.right);
// Delete the inorder successor
root.right = remove(root.right, root.key);
}
return root;
}