#BST0000018. Kiểm tra cây tìm kiếm nhị phân (Validate Binary Search Tree)
Kiểm tra cây tìm kiếm nhị phân (Validate Binary Search Tree)
Validate Binary Search Tree
Source: LeetCode
Version: Phuoc Hung OJ Extended
Problem Statement
A binary tree with nodes is given. It is a valid BST if all of the following conditions hold at every node with key :
- every key in the left subtree is strictly smaller than ;
- every key in the right subtree is strictly greater than ;
- both subtrees satisfy the same definition.
The inequalities are strict, so two equal keys cannot both appear in a valid BST.
Determine whether the given tree is a valid BST.
Input
The first line contains and the root index .
Exactly lines follow. Line describes node as key left right. A child index of means that the child is absent; any nonzero child index is in .
The input is guaranteed to describe exactly one connected, acyclic binary tree rooted at .
Output
Print YES if the tree is a valid BST; otherwise print NO.
Subtasks
Subtask 1 (20 points): .
Subtask 2 (30 points): .
Subtask 3 (50 points): .
In all subtasks, .
Examples
Input
5 1
8 2 3
3 4 5
10 0 0
1 0 0
9 0 0
Output
NO
Explanation
The node with key is in the left subtree of the root with key . A valid BST requires every key in that entire subtree to be smaller than , but .
Therefore the tree is invalid and the output is NO.