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> { public class AVLSearchTree<T extends Comparable<T>> extends SortedBinaryTree<T> {
private boolean balanced(TreeNode<T> node) { private boolean balanced(TreeNode<T> node) {
if(Math.abs(calcHeight(node.right) - calcHeight(node.left)) > 1 if(node == null){
|| (node.right != null && !balanced(node.right)) return true;
|| (node.left != null && !balanced(node.left))){ } 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; return false;
} else { } else {
return true; return true;
@ -23,15 +26,11 @@ public class AVLSearchTree<T extends Comparable<T>> extends SortedBinaryTree<T>
@Override @Override
protected int calcSize(TreeNode<T> p) { protected int calcSize(TreeNode<T> p) {
// Implement (6.2) if (p == null) {
int sizeLeft = 0, sizeRight = 0; return 0;
if(p.left != null){ } else {
sizeLeft = calcSize(p.left); 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 // search right
node.right = removeAt(node.right, x); node.right = removeAt(node.right, x);
} }
// TODO Implement (6.5) // Implement (6.5)
if(!balanced(node)){
node = balance(node);
}
return node; return node;
} }
} }