二叉树后序

public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String[] str = in.nextLine().split(" ");
        List<Integer> res = new ArrayList<>();
        for (String s : str) {
            res.add(Integer.parseInt(s));
        }
        List<Integer> index = new ArrayList<>();
        dfs(res, 0, index);
        res.removeAll(index);  // 需要注意删除对应索引数据的问题
        List<String> ans = new ArrayList<>();
        postTravel(res, 0, ans);  // 递归后序遍历
        System.out.print(String.join(" ", ans));

    }
    private static void dfs(List<Integer> res, int idx, List<Integer> index) {  // 返回叶子节点对应索引
        if (idx >= res.size()) {
            return;
        }
        if (isLeaf(res, idx)) {
            index.add(res.get(idx));
        } else {
            dfs(res, 2 * idx + 1, index);  // 递归左叶子节点
            dfs(res, 2 * idx + 2, index);  // 递归右叶子节点
        }
    }
    private static boolean isLeaf(List<Integer> res, int idx) {  // 判断是否是叶子节点
        return ((2 * idx + 1 >= res.size() ) && (2 * idx + 2 >= res.size()));
    }
    private static void postTravel(List<Integer> res, int idx, List<String> p) { // 递归后序遍历
        if (idx >= res.size()) {
            return;
        }
        postTravel(res, 2 * idx + 1, p);
        postTravel(res, 2 * idx + 2, p);
        p.add(String.valueOf(res.get(idx)));
    }

全部评论
这都是基本的算法题了
点赞 回复 分享
发布于 2022-08-08 14:32

相关推荐

不知道怎么取名字_:两个方向 1.简历针对性准备下 2.面试前也需要准备的 主要还是要看各个公司需求,看公司行业和岗位描述,那里面已经写了对技术的需求,一份简历,不可能和所有嵌入式岗位都匹配的
投递北京经纬恒润科技股份有限公司等公司6个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务