This page is still under construction.

Parts of this page are still being built. What you see may change.

Miswritten DFS

Interview

Time limit1sMemory limit1024 MB

Summary
Given a binary tree and a huge K, find the K-th node visited by a buggy pre-order DFS that recurses into the left child twice, without simulating all visits.
Level

Medium6 of 10

Topics
Tree, DFS, Recursion, Math
Solved
No attempts yet

Problem

Yunee is working on a data structures assignment. Yunee wrote a function DFS that traverses a binary tree in pre-order. However, Yunee's code recursively called DFS on the left subtree twice, by mistake.

function DFS(node v):
    visit v
    if v → left exists:
        DFS(v → left)
        DFS(v → left)
    if v → right exists:
        DFS(v → right)

The pseudocode of Yunee's DFS is as above. Now consider the following example.

If we pre-order traverse the above tree, the nodes 1,2,3,4,51, 2, 3, 4, 5 are visited in order. However, Yunee's DFS visits the nodes 1,2,3,3,4,2,3,3,4,51, 2, 3, 3, 4, 2, 3, 3, 4, 5 in order.

Given a binary tree, find the KK-th node visited by Yunee's DFS. It is guaranteed that KK is not greater than the total number of visits. The nodes are numbered from 11 to NN and the root node is always node 11.

Input

The first line contains two integers NN and KK (1≤N≤105,1≤K≤1018)(1\leq N \leq 10^5, 1\leq K \leq 10^{18}). NN represents the number of nodes in the tree. KK is not greater than the total number of visits.

The next NN lines describe the tree. The ii-th line contains two integers l_il\_i and r_ir\_i (0≤l_i,r_i≤N)(0 \leq l\_i, r\_i \leq N). l_il\_i represents the left child of node ii and r_ir\_i represents the right child of node ii. If there is no corresponding child, 00 is given in place of l_il\_i or r_ir\_i.

The root node is always node 11.

Output

Output the KK-th node visited by Yunee's DFS.

Examples1

  1. Example 1

    Input
    5 9
    2 5
    3 4
    0 0
    0 0
    0 0
    
    Expected output
    4