A binary tree of building-floor sensor ids is given in level-order form (a single line of space-separated tokens, null marking a missing child; every non-null node contributes exactly two following tokens for its children). The tree always has at least one node.
Define a node's height as the number of edges on the longest path from that node down to a leaf in its subtree (a leaf has height 0). The tree is height-balanced if, for every node in the tree, the heights of its left and right subtrees differ by at most 1 (treat a missing child as height -1, so that a leaf has height 0).
Formally: define height(missing child) = -1, and height(node) = 1 + max(height(left), height(right)). The tree is balanced if, at every node, |height(left) - height(right)| <= 1 (again using -1 for a missing child).
If the tree is height-balanced, print its overall height (height(root)). Otherwise, print -1.
Line 1: space-separated level-order tokens describing the binary tree (integers and the token null). The tree has at least 1 node.
A single integer: the tree's height if it is height-balanced, otherwise -1.
Example 1
Input
1 2 3 4
Expected
2
Explanation
Node 2's left subtree (via 4) has height 0, right (missing) has height -1, difference 1, OK. Node 3 is a leaf. Root's left height is 1 (via 2), right height is 0 (via 3), difference 1, OK. The tree is balanced with height 2.
Example 2
Input
1 2 null 3 null null null 4
Expected
-1
Explanation
This is a left-leaning chain 1->2->3->4, so at the root, the left subtree has height 2 while the right (missing) has height -1, a difference of 3. The tree is not balanced, so print -1.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →