【indeed】C

来源:互联网 发布:php怎么找工作 编辑:程序博客网 时间:2024/06/03 23:01

C - Binary Tree


Time limit : 2sec / Memory limit : 256MB
Score : 100 points
Problem Statement
You are given a binary tree with N vertices.(树有N个节点)

In the given binary tree, the left child of vertex i (1≤i≤N) is vertex li, and the right child is vertex ri. Here, the value of li may be 0, which means that vertex i does not have a left child. Similarly, the value of ri is 0 if vertex i does not have a right child. The root of the tree is vertex 1.
Find the path from vertex 1 to vertex K when it is possible to move from a vertex to its left or right child. (This path always exists.)
Constraints
• 1≤N≤105
• 1≤K≤N
• 0≤li,ri≤N
• All input values are integers.
• The input corresponds to a valid binary tree.
• Vertex 1 is the root of the tree.


Input
Input is given from Standard Input in the following format:
N K
l1 r1
:
lN rN
Output
Print a string S that represents a path starting at vertex 1 and ending at vertex K. The i-th character should correspond to the i-th move. Use the following characters to represent a move:
• L: a move to the left child
• R: a move to the right child


Sample Input 1

6 6
2 3
4 5
6 0
0 0
0 0
0 0
Sample Output 1

RL
The binary tree given in this input is shown in the following figure:
这里写图片描述

The path from vertex 1 to vertex K=6 is 1 → 3 → 6, and thus the output should be RL.


Sample Input 2

7 2
2 6
3 4
0 0
0 0
0 0
5 7
0 0
Sample Output 2
L


Sample Input 3

10 10
0 2
3 0
0 4
5 0
6 0
0 7
8 0
0 9
10 0
0 0
Sample Output 3
RLRLLRLRL

====
解题思路:
注意树中第N个节点的值即为N,且数据两两一行,每行表示第N个节点的左右子节点。所以可以根据行中左右位置,得到该节点是其父节点的左或右节点,再根据其所在行,得到其父节点位置。

数据结构使用list。输出使用StringBuilder(线程不安全)。

一定要结合输入来写逻辑,行号之类的很容易错。

import java.util.*;/** * Created by eli on 2017/5/27. */public class indeed0517_3 {    public static void main(String[] args) {        StringBuilder result = new StringBuilder();        Scanner sc = new Scanner(System.in);        int N = sc.nextInt();        int K = sc.nextInt();        ArrayList<Integer> list = new ArrayList<>(2*N);        for(int i = 0; i<2*N; i++){            list.add(sc.nextInt());        }        int index;        while(K!=1){             index = list.indexOf(K);            if(index%2==0)                result.append("L");            else                result.append("R");            K =(int)Math.ceil(index/2)+1;        }        result.reverse();        System.out.println(result);    }}
原创粉丝点击