Binary Search Tree
Time limit2sMemory limit512 MB
Given a tree with n vertices labeled 1 to n, find every vertex that can be the root of a binary search tree on those labels, or report -1.
- Level
Medium7 of 10
- Topics
- Tree, Dynamic programming, DFS
- Solved
- No attempts yet
Problem
How to check if a tree is a binary search tree?
Someone in a Telegram chat
A binary search tree is a rooted tree in which:
- each vertex has at most one left child and at most one right child,
- for each non-leaf vertex , all vertices in its left subtree are less than , and all vertices in its right subtree are greater than .
You are given a tree with vertices. Can this tree be a binary search tree when rooted at some vertex? If so, which vertices can be the root?
Input
The first line contains an integer (), the number of vertices in the tree.
Each of the next lines contains two integers and (), an edge of the tree.
Output
If the tree cannot be a binary search tree, print -1.
Otherwise, print all vertices that can be the root, in increasing order.