All problems

Problem 152

Validate Binary Search Tree

Medium · 20 pts · Tree, Binary Search Tree, Depth-First Search

Problem

You are given a binary tree. Decide whether it is a valid binary search tree: for every node, all values in its left subtree must be strictly smaller than the node's value, and all values in its right subtree must be strictly larger. Comparing each node only with its direct children is not enough, because a value deep in a subtree can break the rule with an ancestor. Pass down an allowed range (low, high) for each node, or check that the inorder traversal is strictly increasing.

Input

First line: integer N, the number of tokens. Second line: N tokens describing the tree in level order, where 'null' marks a missing child (the same format LeetCode uses).

Output

Print YES or NO.

Constraints

1 <= number of nodes <= 10000; -1000000000 <= value <= 1000000000

Example input

3
2 1 3

Example output

YES

Explanation

The root 2 has left child 1 and right child 3. Since 1 < 2 < 3 and there are no other nodes, every rule holds, and the answer is YES.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Path Sum Next: Lowest Common Ancestor of a BST