Is It Really a Search Tree?
Someone built a binary tree and swears it is a binary search tree. You are given the tree exactly as they built it — every node's key and its two children — and asked to check their claim.
A binary tree is a strict binary search tree (BST) if, for every node v:
- every key in
v's left subtree is strictly less thanv's key, and - every key in
v's right subtree is strictly greater thanv's key.
(This must hold for the entire subtree on each side, not just the immediate children — a key several levels down can still break the rule set by a far ancestor.)
If the tree is a strict BST, report that. Otherwise, report the first node that breaks the rule, where "first" means first encountered in a preorder traversal: visit a node, then recursively visit its whole left subtree, then its whole right subtree, starting from the root.
Input
The first line contains an integer n (1 ≤ n ≤ 2·10^5) — the number of nodes.
Each of the next n lines describes one node. Nodes are numbered 1 to n by the order they
appear: the i-th of these lines contains three integers key_i, l_i, r_i
(-10^9 ≤ key_i ≤ 10^9, 0 ≤ l_i, r_i ≤ n) — the key stored at node i, and the ids of its left
and right children, or 0 if a child is absent.
It is guaranteed that the n nodes form a single valid binary tree rooted at node 1 (every other
node is the child of exactly one node, and there are no cycles). Keys are not guaranteed to be
distinct, and the tree is not guaranteed to be a BST — that is exactly what you must decide.
Output
If the tree is a strict BST, print YES.
Otherwise, print NO on the first line, then on the second line the id of the first node (in the
preorder order described above) whose key violates a bound inherited from one of its ancestors.
Notes
In the second example, node 3 (key 15) is the right child of node 2 (key 5), which is itself
the left child of the root, node 1 (key 10). Checking node 3 only against its immediate parent
(15 > 5) looks fine, but node 3 lies in the root's left subtree, so its key must also be below
the root's key 10. Since 15 ≥ 10, node 3 is the violation — and it is the first one encountered
in preorder, since nodes 1 and 2 both satisfy every bound inherited from their own ancestors.