Under construction

Still being built. Things may change

Binary Search Tree

Time limit2sMemory limit512 MB

Summary
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 xx, all vertices in its left subtree are less than xx, and all vertices in its right subtree are greater than xx.

You are given a tree with nn 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 nn (1≤n≤5000001 \le n \le 500000), the number of vertices in the tree.

Each of the next n−1n - 1 lines contains two integers uiu_i and viv_i (1≤ui,vi≤n1 \le u_i, v_i \le n), 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.

Examples4

  1. Example 1

    Input
    3
    1 2
    2 3
    
    Expected output
    1 2 3
    
  2. Example 2

    Input
    3
    1 3
    3 2
    
    Expected output
    1
    
  3. Example 3

    Input
    4
    1 3
    3 2
    2 4
    
    Expected output
    -1
    
  4. Example 4

    Input
    4
    1 2
    1 3
    1 4
    
    Expected output
    -1