← Back to problems
UNSW COMP2521 · easy

Binary Tree: Height

Binary Tree: Height

Insert the given integers, in input order, into a Binary Search Tree (BST). Complete the height function so it returns the tree's height.

Height is measured in edges: a single node (leaf) has height 0, and the empty tree has height -1.

This is exactly the recursion shown in this topic: return -1 for the empty tree, otherwise 1 + max(left, right). Forgetting the -1 base case is the classic segfault.

Input

  • Line 1: integer n (number of nodes, may be 0).
  • Line 2: n space-separated integers, inserted into the BST in this order.

Output

  • One line: the height of the tree.

Example: input 5 / 50 30 70 20 40 → output 2 (longest root→leaf path 50→30→20 has 2 edges).