DSAA B第三次assignment q1 parents(南科大)

一. Problem Description

Given a rooted binary tree from to , the root node of the tree is node . You are asked to print

the parent node of every node in the binary tree.

Input

The first line contains one integer n , indicating the number of tree nodes.

Then n-1 lines follow. Each line contains two integers v&&w are the indices of nodes that form an edge.

Output

An array containing n integers, the element ith of which represents the parent node of nodes

from 1 to n in order in the binary tree. Note that for node 1 , which is the root node of the tree,

the parent should output -1

Sample input

6
1 2
1 3
3 4
3 5
2 6

Sample output

-1 1 1 3 3 2

二. 解题思路

1.使用无向图构建树

2.使用内存占用较少的adjacent list 构建树枝

3.使用dfs深度优先递归树,以切断所有树枝为结尾的同时创建parent[]作为返回数组。

三.代码示例

import java.io.File;
import java.io.FileNotFoundException;
import java.util.LinkedList;
import java.util.Scanner;

public class Parents {
 public static void main(String[] args) throws FileNotFoundException {
        // 文件中第一个数字是数组长度,接下来N个数字才是数组元素。
        // 请根据实际情况更改file的文件路径
            File input = new File("test_data/Q1/A1.in");
        if (!input.exists()) {
            System.out.println("File isn't exist");
            System.exit(0);
        }
        Scanner in = new Scanner(input);
        int n = in.nextInt();  //the number of tree nodes
        LinkedList<Integer>[] list=new LinkedList[n+1];
        for (int i = 0; i <n+1 ; i++) {
            list[i]=new LinkedList<>();
        }
        for (int i = 0; i < n-1; i++) {
            int father=in.nextInt();
            int child=in.nextInt();
            list[father].add(child);
            list[child].add(father);
        }//创建简单树,进行树枝连接
        int[] parents = findParents(n, list);//调用函数求解
        File output = new File("test_data/Q1/A1.out");
        in = new Scanner(output);
        boolean flag = true;
        for (int i = 0; i < n; i++) {
            if (in.nextInt() != parents[i]) {
                flag = false;
                break;
            }
        }
        System.out.println(flag);//与答案对比,验证准确性
    }
    public static int[] findParents(int n, LinkedList<Integer>[] list) {
//使用递归,从1开始,list[1]中的所有元素进行递归,直到递归完毕n个元素,同时数组创建成功
        int[] parents = new int[n];
        parents[0]=-1;
       while (list[1].size()!=0){
           pdfs(parents,list,1);
       }
        return parents;
    }
public static void pdfs( int[] parents, LinkedList<Integer>[] list,int father){
        int a=list[father].get(0);
        parents[a-1]=father;
        list[father].remove(0);
    for (int i = 0; i < list[a].size(); i++) {
        if (list[a].get(i)==father) list[a].remove(i);
    }
   while (list[a].size()!=0){
   pdfs(parents,list,a);
   }
}
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值