CJCoding With Joseph
15free / daySign inCreate account

Measure the Height of a BST

Complete the private helper height(Node node) so that height() returns the height of the tree.

Reminder: the height of a tree. Here the height is the number of nodes on the longest path from the root down to a leaf. An empty tree has height 0 and a tree with only a root has height 1. Height matters because a search walks one path from the root downwards, so the height is the most steps a search can ever take.

balanced, height 3:
        40
       /  \
     20    60
    /  \     \
  10    30    70

sorted inserts 10, 20, 30, 40, height 4:
  10
    \
     20
       \
        30
          \
           40

The order you insert values in decides the shape. Inserting values that are already sorted builds a tall, thin "stick" that is no faster to search than a linked list. Keeping trees short is exactly the job of the AVL trees later in this tile.

A node's height is 1 (for the node itself) plus the height of its TALLER subtree.

Requirements: 1. Return 0 when node is null. 2. Otherwise work out the height of the left subtree and of the right subtree, and return 1 plus the larger of the two (Math.max is handy). 3. Use recursion.

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:

0
1
2
3
4

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

Hints4 available
Topics:
Data Structures & AlgorithmsBinary Search 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.