我在旋轉(zhuǎn)樹和返回旋轉(zhuǎn)的樹時遇到問題。幾乎在將新樹插入到我的 AVL 后,我檢查平衡是否小于 -1 并且父高度小于 0,這是正確的情況,我需要實現(xiàn)向左旋轉(zhuǎn)。我需要幫助理解為什么我的左旋轉(zhuǎn)不起作用以及如果它起作用為什么我沒有得到旋轉(zhuǎn)的樹的回報。public class AVLTree < T extends Comparable < T >> extends BinaryTree < T> {private int balance ;private AVLTree < T> parent;public AVLTree(T item){ this(item,null);}public AVLTree(T item, AVLTree<T> parent){ super(item); this.balance = 0; this.parent = parent; }public AVLTree<T> insert(T item){ updateHeight(this); if(this.item.compareTo(item) < 0){ if(this.left != null){ this.left.insert(item); } else{ this.left= new AVLTree<T>(item, this); } return rotations((AVLTree<T>)this.left); } else{ if(this.right != null){ this.right.insert(item); } else{ this.right = new AVLTree<T>(item, this); } return rotations((AVLTree<T>)this.right); } } private AVLTree<T> rotateLeft(AVLTree<T> x){AVLTree<T> temp = (AVLTree<T>)x.parent;AVLTree<T> an = (AVLTree<T>)temp.left; //rotationtemp.left = x;temp.right = x.parent.right;x.right = an;//update heightsupdateHeight(x);updateHeight(temp);//return new rootreturn temp;}public AVLTree<T> rotations(AVLTree<T> input){ int balance = getBalance(input);//Right Rightif (balance < -1 && ph() < 0){ return input =rotateLeft(input);}return input;}public void updateHeight(AVLTree<T> current){ current.height = Math.max(height((AVLTree<T>)current.left), height((AVLTree<T>)current.right)) + 1;}public int getBalance(){ return getBalance(this);}public int getBalance(AVLTree<T> current){ return (current == null)? 0 : height((AVLTree<T>)current.right) - height((AVLTree<T>)current.left);}public int ph(){ return lbal()-rbal();}int lbal(){ if(this.right== null){ return 0; } return (height(this.right));}int rbal(){ if(this.left == null){ return 0; } return height(this.left);}
2 回答

小唯快跑啊
TA貢獻1863條經(jīng)驗 獲得超2個贊
問題是搜索功能BinaryTree<T> find(T item)
是在父類中實現(xiàn)的BinaryTree
,而這個類應該對子類一無所知AVLTree
。
該find()
方法返回 a BinaryTree
,因此即使您構(gòu)造了 的實例AVLTree
,當您調(diào)用時,find()
您也會得到 a BinaryTree
。
假設AVLTree<T> insert(T item)
實現(xiàn)是正確的,樹節(jié)點正在正確組裝,因此您可以簡單地將調(diào)用結(jié)果類型find()
轉(zhuǎn)換為AVLTree
添加回答
舉報
0/150
提交
取消