华为od机考_传递悄悄话_Java(二叉树构建及求高度)

华为od机考_传递悄悄话_Java(二叉树构建及求高度)

题目

给定一个二叉树,每个节点上站着一个人,节点数字表示父节点到该节点传递情悄诺需要花费的时间。 初始时,根节点所在位置的人有一个悄悄话根要传递给其他人,求二又树所有节点上的人都接收到悄悄话花费的时间。 输入描述: 给定二叉树 0 9 20 -1 -1 15 7 -1 -1 -1 -1 3 2 注:-1表示空节点

输出描述: 返回所有节点都接收到悄悄活花费的时间38

示例一

输入

0 9 20 -1 -1 15 7 -1 -1 -1 -1 3 2

输出

38

代码

public class Test9 {
    static class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;
        public TreeNode(int val) {
            this.val = val;
        }
    }

    /**
     * 构建二叉树
     * 使用层序遍历(宽度优先遍历)的方法将数组中的值转换为二叉树的节点。
     * -1 表示空节点。
     * @param nodes
     * @return
     */
    public static TreeNode buildTree(Integer[] nodes) {
        if (nodes.length == 0) return null;

        TreeNode root = new TreeNode(nodes[0]);
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int i = 1;

        while (!queue.isEmpty() && i < nodes.length) {
            TreeNode current = queue.poll();
            if (nodes[i] != null) {
                current.left = new TreeNode(nodes[i]);
                queue.add(current.left);
            }
            i++;
            if (i < nodes.length && nodes[i] != null) {
                current.right = new TreeNode(nodes[i]);
                queue.add(current.right);
            }
            i++;
        }
        return root;
    }

    // 计算最大路径长度
    public static int maxTime(TreeNode root) {
        if (root == null || root.val == -1) return 0;

        int left = maxTime(root.left);
        int right = maxTime(root.right);

        return root.val + Math.max(left, right);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        String[] inputArray = input.split(" ");
        Integer[] nodes = new Integer[inputArray.length];
        for (int i = 0; i < inputArray.length; i++) {
            nodes[i] = Integer.parseInt(inputArray[i]);
        }

        TreeNode root = buildTree(nodes);
        int result = maxTime(root);

        System.out.println(result);
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值