We then override the setLeftChild() and setRigthChild() methods such that the height of this node gets adjusted accordingly with the new child by calling the resetHeights() method:
@OverridepublicvoidsetLeftChild(AVLNode<T> node) { super.setLeftChild(node);resetHeights();}@OverridepublicvoidsetRightChild(AVLNode<T> node) { super.setRightChild(node);resetHeights();}/** Resets the heights of this node and its ancestor, recursively. */publicvoidresetHeights() {resetHeightsAux(this);}privatevoidresetHeightsAux(AVLNode<T> node) {if (node !=null) {int lh =node.hasLeftChild() ?node.getLeftChild().getHeight() :0;int rh =node.hasRightChild() ?node.getRightChild().getHeight() :0;int height =Math.max(lh, rh) +1;if (height !=node.getHeight()) {node.setHeight(height);resetHeightsAux(node.getParent()); // recursively update parent height } }}
L15: adjusts the height of this node and its ancestors, recursively.
L20-22: retrieve the height of this node.
L24-27: resets the height of this node if different and makes the recursive call to its parent.
What are the heights of 3, 5, and 7 in the figure below when the height of 4 changes from 3 to 4?
Finally, we define the getBalanceFactor() method that returns the height difference between the left-subtree and the right-subtree of this node: