Skip to content

ORIGINAL CODING QUESTION

Evenly staffed binary chart

Call a binary chart evenly staffed when, at EVERY node, the heights of its left and right subtrees differ by at most 1. Height counts nodes on the longest downward path, and an empty subtree has height 0. Print 1 if the chart is evenly staffed, otherwise 0. Checking only the root is not enough.

Open practice workspace

Original exercise · easy. Editorial role relevance does not imply a company has asked this question.

Input and output

n, then n triples (value,leftChild,rightChild). Node 0 is the root; a missing child is written as -1.

Constraints

1 ≤ n ≤ 200; -100 ≤ value ≤ 100; the triples form one connected binary tree and every child ID is larger than its parent ID.

Example 1

Input

7 1 1 2 2 3 4 3 5 6 4 -1 -1 5 -1 -1 6 -1 -1 7 -1 -1

Output

1

Every node has two subtrees of equal height.

Example 2

Input

4 1 1 -1 2 2 -1 3 3 -1 4 -1 -1

Output

0

The root has a left subtree of height 3 and an empty right subtree.

Explain your approach

Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?

Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.

Hint 1

A node needs the heights of both of its subtrees.

Hint 2

Children have larger IDs, so processing IDs from n-1 down to 0 is a valid bottom-up order.

Hint 3

Record a failure as soon as any node breaks the rule, but keep computing heights.

Practice this question

Save your work privately, explain decisions and return to your revision queue.

Open practice workspaceBrowse the question library →