All problems

Problem 928

Validate Binary Tree Nodes

Medium · 20 pts · Tree, Graph, Union Find, Breadth-First Search

Problem

There are N nodes numbered 0 to N - 1. Node i has the left child LEFT[i] and the right child RIGHT[i], where -1 means no child. Decide whether all the nodes together form exactly one valid binary tree. That requires exactly one node with no parent (the root), no node with two parents, and every node reachable from the root, which also rules out cycles. Count parents, find the root, and run a search from it.

Input

The first line contains N. The second line contains LEFT[0..N-1]. The third line contains RIGHT[0..N-1].

Output

Print YES if the nodes form exactly one valid binary tree, otherwise NO.

Constraints

1 <= N <= 10000; -1 <= LEFT[i], RIGHT[i] < N

Example input

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

Example output

YES

Explanation

With LEFT = 1 -1 3 -1 and RIGHT = 2 -1 -1 -1, node 0 has children 1 and 2, and node 2 has child 3. Every node has one parent except the root 0, and all are reachable, so the answer is YES.

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

Previous: Find Leaves of Binary Tree Next: Keys and Rooms