根节点到最小的叶子节点的路径

import java.util.*; public class Main {

static List<Integer> pList = new ArrayList<>();
public static void main(String[] args){
    Scanner in = new Scanner(System.in);
    while(in.hasNextInt()){
        pList.clear();
        int n = in.nextInt();
        int[] arr = new int[n];
        ArrayList<Integer> list = new ArrayList<>();
        for(int i=0; i<n; i++){
            arr[i] = in.nextInt();
        }
        dfs(0, list, arr);
        for(int p:pList){
            System.out.print(p + " ");
        }
    }
}

public static void dfs(int i, ArrayList<Integer> list, int[] arr){
    if(!list.isEmpty() && list.get(list.size()-1)==-1) return;
    if(i >= arr.length){
        if(pList.isEmpty()||pList.get(pList.size()-1)>list.get(list.size()-1)){
            pList.addAll(list);
        }
    } else {
        list.add(arr[i]);
        dfs(2*(i+1)-1, list, arr);
        dfs(2*(i+1), list, arr);
        list.remove(list.size()-1);
    }

}

}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务