Re-balance tree after node removal

This commit is contained in:
Manuel Thalmann 2022-10-31 21:46:05 +01:00
parent 532788980e
commit ac7372738c

View file

@ -3,13 +3,20 @@ package ch.nuth.zhaw.exbox;
/** /**
* Implements an AVL tree. * Implements an AVL tree.
* Note that all "matching" is based on the compareTo method. * Note that all "matching" is based on the compareTo method.
*
* @author Mark Allen Weiss * @author Mark Allen Weiss
* Generic K.Rege * Generic K.Rege
*/ */
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) {
// TODO Implement (6.4) // TODO Implement (6.4)
return true; if (node == null) {
return true;
} else if (balanced(node.left) && balanced(node.right)) {
return Math.abs(calcHeight(node.left) - calcHeight(node.right)) < 2;
} else {
return false;
}
} }
public boolean balanced() { public boolean balanced() {
@ -31,6 +38,7 @@ public class AVLSearchTree<T extends Comparable<T>> extends SortedBinaryTree<T>
/** /**
* Insert into the tree; duplicates are ignored. * Insert into the tree; duplicates are ignored.
*
* @param element the item to insert. * @param element the item to insert.
*/ */
public void add(T element) { public void add(T element) {
@ -63,8 +71,9 @@ public class AVLSearchTree<T extends Comparable<T>> extends SortedBinaryTree<T>
/** /**
* Internal method to insert into a subtree. * Internal method to insert into a subtree.
*
* @param element the item to insert. * @param element the item to insert.
* @param p the node that roots the tree. * @param p the node that roots the tree.
* @return the new root. * @return the new root.
*/ */
private TreeNode<T> insertAt(TreeNode<T> p, T element) { private TreeNode<T> insertAt(TreeNode<T> p, T element) {
@ -88,6 +97,7 @@ public class AVLSearchTree<T extends Comparable<T>> extends SortedBinaryTree<T>
// find node to replace // find node to replace
private TreeNode<T> rep; private TreeNode<T> rep;
private TreeNode<T> findRepAt(TreeNode<T> node) { private TreeNode<T> findRepAt(TreeNode<T> node) {
if (node.right != null) { if (node.right != null) {
node.right = findRepAt(node.right); node.right = findRepAt(node.right);
@ -129,13 +139,15 @@ 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) // TODO Implement (6.5)
return node; return balance(node);
} }
} }
/** /**
* Remove from the tree. Nothing is done if x is not found. * Remove from the tree. Nothing is done if x is not found.
*
* @param x the item to remove. * @param x the item to remove.
*/ */
public T remove(T x) { public T remove(T x) {