Validate a binary search tree · Compiler

Validate a binary search tree

A strict BST requires every key in a node's left subtree to be smaller than its key, and every key in its right subtree to be larger. Inspect the nodes in preorder (node, left subtree, right subtree). Report the first node whose key violates any bound inherited from its ancestors. Equality with a bound is a violation.

Input
Read n (0 <= n <= 100), then n rows of value left right. Rows give nodes in ID order from 1 to n. Each value is an integer in [-1000, 1000]. Each child link is a node ID or 0 for a missing child. For n > 0, the links form one binary tree rooted at ID 1.
Output
Print the key of the first violating node, or VALID if every node satisfies its bounds. An empty tree is valid.

Compiler Explorer runs your code when you run or check it.

Loading your exercise draft…