Skip to content

ORIGINAL CODING QUESTION

Strict search-tree check

Print 1 if the supplied binary tree satisfies strict BST ordering, otherwise 0. Every value in a left subtree must be smaller and every value in a right subtree larger; duplicates invalidate it.

Open practice workspace

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

Input and output

n, then n triples (value,leftChild,rightChild). Root is node 0; missing children use -1.

Constraints

1 ≤ n ≤ 200; -100 ≤ value ≤ 100; input is a valid connected binary tree, every child ID is larger than its parent ID.

Example 1

Input

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

Output

1

The left and right values satisfy strict bounds.

Example 2

Input

3 5 1 -1 3 -1 2 7 -1 -1

Output

0

Node 7 is inside the left subtree of 5, so invalid.

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

Checking only immediate children is insufficient.

Hint 2

Pass inherited lower and upper bounds down the tree.

Hint 3

Use strict bounds to reject duplicates.

Practice this question

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

Open practice workspaceBrowse the question library →