CJCoding With Joseph
15free / daySign inCreate account

Update an AVL Node's Height

Complete updateHeight(Node node) so every node's stored height stays correct while values are inserted.

Reminder: what an AVL tree is. An AVL tree is a binary search tree that keeps itself balanced, so it never turns into a long, slow chain. To notice when it is getting lopsided, every node stores its own height: the number of nodes on the longest path from that node down to a leaf. A leaf has height 1, and an empty child counts as 0. This tree does not rotate yet - it inserts exactly like a plain BST - so this question is only about keeping the heights right.

          50(h3)
         /      \
     30(h2)    70(h1)
      /
  20(h1)

A node's height depends only on its two children: it is one more than the taller child. insert already calls updateHeight on every node it passes on the way back up from the new leaf, so the children are always up to date before their parent is.

Requirements: 1. Read the heights of node.left and node.right with the provided height(Node) helper, which returns 0 for null. 2. Set node.height to 1 plus the larger of the two. 3. Do not change insert or any other method.

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:

50(h3) 30(h2) 20(h1) 70(h1)
3
50(h4) 30(h3) 20(h2) 10(h1) 70(h1)
4

= 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.