首页 > 试题广场 >

二叉树中的最大路径和

[编程题]二叉树中的最大路径和
  • 热度指数:2272 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
二叉树里面的路径被定义为:从该树的任意节点出发,经过父=>子或者子=>父的连接,达到任意节点的序列。
注意:
1.同一个节点在一条二叉树路径里中最多出现一次
2.一条路径至少包含一个节点,且不一定经过根节点

给定一个二叉树,请你计算它的最大路径和
例如:
给出以下的二叉树,

最优路径是:2=>1=>3,或者3=>1=>2,最大路径和=2+1+3=6

数据范围:节点数满足 ,节点上的值满足
要求:空间复杂度 ,时间复杂度

输入描述:
第一行输入一个正整数 n 表示二叉树的节点数
第二行输入 n 个整数表示二叉树上第 i 个节点的值
第三行输入 n 个整数表示二叉树上第 i 个节点的父节点是第几个节点,(其中第一个节点是根节点,其父节点表示为第零个节点0)。


输出描述:
输出最大路径和
示例1

输入

3
1 2 3
0 1 1

输出

6
示例2

输入

5
-20 8 20 15 6
0 1 1 3 3

输出

41

说明

其中一条最大路径为:15=>20=>6,路径和为15+20+6=41   
示例3

输入

2
-2 -3
0 1

输出

-2
import java.util.*; 

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    static class Node {
        public Node(int val) {
            this.val = val;
        }
        public int val;
        public Node left;
        public Node right;
    }
    public static int ans = Integer.MIN_VALUE;
    public static Map<Integer, Node> map = new HashMap<>();
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        int nodeNum = in.nextInt();
        in.nextLine();
        if (nodeNum == 0) {
            return;
        }
        int[][] child = new int[nodeNum][2];
        String[] strings1 = in.nextLine().split(" ");
        String[] strings2 = in.nextLine().split(" ");
        for (int i = 1; i <= nodeNum; i++) {
            map.put(i, new Node(Integer.valueOf(strings1[i-1])));
            if (map.get(Integer.valueOf(strings2[i-1])) != null) {
                if (map.get(Integer.valueOf(strings2[i-1])).left == null) {
                    map.get(Integer.valueOf(strings2[i-1])).left = map.get(i);
                } else {
                    map.get(Integer.valueOf(strings2[i-1])).right = map.get(i);
                }
            }
        }

        
        Node root = map.get(1);
        dfs(root);
        System.out.println(ans);
    }

    public static int dfs(Node root) {
        if (root == null) {
            return 0;
        }
        int maxL = Math.max(dfs(root.left), 0);
        int maxR = Math.max(dfs(root.right), 0);

        ans = Math.max(ans, root.val + maxL + maxR);
        return Math.max(root.val + maxL, root.val + maxR);
    }
}

发表于 2024-01-13 23:18:16 回复(0)