CJCoding With Joseph
15free / daySign inCreate account

Check That Every Node Is Balanced

Complete isBalanced(Node node) so isAVL() reports whether every node in the tree obeys the AVL balance rule.

Reminder: the AVL balance rule. In an AVL tree every node's balance factor, height(left) - height(right), must be -1, 0 or 1. Heights count nodes (a leaf is 1, an empty child is 0). This tree inserts like a plain BST and does not rotate yet, so some inserts break the rule. Your method is the check that tells you a rotation is needed.

Checking only the root is not enough. In this tree the root's balance factor is 1, which is fine, but node 30 has a balance factor of 2:

            50
           /  \
         30    70
        /     /  \
      20    60    80
     /
   10

So a tree passes only when its root passes AND its left subtree passes AND its right subtree passes - the same shape of recursion you use to count the nodes of a tree.

Requirements: 1. Return true for null: an empty subtree is balanced. 2. Return false when the node's balance factor, from the provided balanceFactor(Node), is less than -1 or greater than 1. 3. Otherwise return true only if both node.left and node.right are balanced, checked with recursion. 4. Do not change insert or the height helpers.

The provided preOrder() lists every node in pre-order as its value followed by its height, for example 30(h2).

The Node class is provided - do not rename it and do not add public to it, because a Java source file may contain only one public class.

Do NOT write a main method.

Expected Output:

true
true
false

= newline. The output ends with a newline — print one after the last line.

Hints4 available
Topics:
Data Structures & AlgorithmsAVL Trees
1
Tab to indent (Esc then Tab to move on) · Ctrl+Enter to run · Shift+Alt+F to format · Ctrl+Space to expand shortcuts (sysout, psvm, fori)

Your Output

Run your code to see the output here...

Test Cases

Run your code to see test case results.