我遇到了这个关于为泛型类型二叉搜索树实现删除方法的实验室问题。
我已经实现了泛型类型的二叉搜索树。
我已经学习了二叉搜索树删除算法,并且我尝试处理父节点具有“0子节点”,“1子项”或“2个子项”的3种情况。
我实现代码以删除节点,但不断导致堆栈溢出问题,并且我无法在代码中找到错误的地方。
任何帮助将不胜感激。
public class BinarySearchTree<T extends Comparable<T>> {
private Node<T> _root; //Root node
public class Node<T extends Comparable<T>> {
public T get_value() {return _value;}
public void set_value(T _value) {this._value = _value;}
public Node<T> get_left() {return _left;}
public void set_left(Node<T> _left) {this._left = _left;}
public Node<T> get_right() {return _right;}
public void set_right(Node<T> _right) {this._right = _right;}
public Node<T> get_parent() {return _parent;}
public void set_parent(Node<T> _parent) {this._parent = _parent;}
T _value; // Node value
Node<T> _left; // Left child
Node<T> _right; // Right child
Node<T> _parent; // Parent node
public Node(T key, Node<T> parent, Node<T> left, Node<T> right) {
_value = key;
_left = left;
_right = right;
_parent = parent;
}
}
// Remove a node from the BST
private Node<T> remove(BinarySearchTree<T> bst, Node<T> z) {
Node<T> delNode = null;
if(bst._root == null){
delNode = null;
}
else{
Node<T> current = bst._root;
// find the position to delete
while(current!=null){
int compare = z.get_value().compareTo(current.get_value());
if(compare < 0){
current = current.get_left();
}
if(compare > 0){
current = current.get_right();
}
慕姐8265434
青春有我
随时随地看视频慕课网APP
相关分类