我遇到了這個關于為泛型類型二叉搜索樹實現刪除方法的實驗室問題。我已經實現了泛型類型的二叉搜索樹。我已經學習了二叉搜索樹刪除算法,并且我嘗試處理父節點具有“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(); }
1 回答

青春有我
TA貢獻1784條經驗 獲得超8個贊
您的條件有問題。它們應該是:
if(compare < 0) { current = current.get_left(); } else if(compare > 0) { current = current.get_right(); } else { ...
就像現在一樣,如果 是 ,則同時執行子句和子句。compare < 0
true
current = current.get_left();
else
不過,我不確定這是你的方法的唯一問題。remove
添加回答
舉報
0/150
提交
取消