solved Task 5

This commit is contained in:
schrom01 2022-10-25 19:45:21 +02:00
parent 87da5e2551
commit dbf0186898
1 changed files with 14 additions and 12 deletions

View File

@ -8,9 +8,12 @@ package ch.zhaw.ads;
*/
public class AVLSearchTree<T extends Comparable<T>> extends SortedBinaryTree<T> {
private boolean balanced(TreeNode<T> node) {
if(Math.abs(calcHeight(node.right) - calcHeight(node.left)) > 1
|| (node.right != null && !balanced(node.right))
|| (node.left != null && !balanced(node.left))){
if(node == null){
return true;
} else if (Math.abs(calcHeight(node.right) - calcHeight(node.left)) > 1
// || (node.right != null && !balanced(node.right))
// || (node.left != null && !balanced(node.left))
){
return false;
} else {
return true;
@ -23,15 +26,11 @@ public class AVLSearchTree<T extends Comparable<T>> extends SortedBinaryTree<T>
@Override
protected int calcSize(TreeNode<T> p) {
// Implement (6.2)
int sizeLeft = 0, sizeRight = 0;
if(p.left != null){
sizeLeft = calcSize(p.left);
if (p == null) {
return 0;
} else {
return p.values.size() + calcSize(p.left) + calcSize(p.right);
}
if(p.right != null) {
sizeRight = calcSize(p.right);
}
return sizeLeft + sizeRight + 1;
}
/**
@ -140,7 +139,10 @@ public class AVLSearchTree<T extends Comparable<T>> extends SortedBinaryTree<T>
// search right
node.right = removeAt(node.right, x);
}
// TODO Implement (6.5)
// Implement (6.5)
if(!balanced(node)){
node = balance(node);
}
return node;
}
}