#BST0000012. Kiểm tra một cây có phải BST (Validate a Binary Search Tree)
Kiểm tra một cây có phải BST (Validate a Binary Search Tree)
Validate a Binary Search Tree
Source: Phuoc Hung OJ
Version: Phuoc Hung OJ Extended
Problem Statement
A binary tree with indexed nodes is given directly. Each node has an integer key and may have a left child and a right child.
The tree is a strict BST if, for every node with key :
- every key in its entire left subtree is smaller than ;
- every key in its entire right subtree is greater than .
The rule applies to all descendants, not only to direct children. A tree may therefore satisfy every direct parent-child comparison and still fail the BST condition because of a deeper descendant.
Determine whether the given tree is a strict BST.
Input
The first line contains and the root index . If , then .
If , exactly lines follow. Line describes node as key left right:
key is the key of node ;
left is its left-child index;
right is its right-child index.
Index means that the corresponding child is absent. Any nonzero node index is in .
The input is guaranteed to describe exactly one rooted binary tree: it is connected, acyclic, and every non-root node has exactly one parent. Node keys are not guaranteed to be distinct.
Output
Print YES if the tree is a strict BST; otherwise print NO.
Subtasks
Subtask 1 (20 points): .
Subtask 2 (30 points): .
Subtask 3 (50 points): .
In all subtasks, every key is a signed 64-bit integer.
Examples
Input
5 1
8 2 3
3 4 5
10 0 0
1 0 0
9 0 0
Output
NO
Explanation
Node is the root with key . Node is below node , so it still belongs to the entire left subtree of the root.
However, node has key . A key greater than appears in the root's left subtree, so the strict BST condition is violated and the output is NO.