zoukankan      html  css  js  c++  java
  • 0124. Binary Tree Maximum Path Sum (H)

    Binary Tree Maximum Path Sum (H)

    题目

    A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.

    The path sum of a path is the sum of the node's values in the path.

    Given the root of a binary tree, return the maximum path sum of any path.

    Example 1:

    Input: root = [1,2,3]
    Output: 6
    Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.
    

    Example 2:

    Input: root = [-10,9,20,null,null,15,7]
    Output: 42
    Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.
    

    Constraints:

    • The number of nodes in the tree is in the range [1, 3 * 10^4].
    • -1000 <= Node.val <= 1000

    题意

    给定一个二叉树,在树中找到任意一条路径(起点随意,终点随意),使得这条路径上结点值的和最大。


    思路

    递归处理。对于一个以 root 为根结点的子树,我们计算以 root.left 为起点并向下延伸的路径的最大和 a,以及以 root.right 为起点并向下延伸的路径的最大和 b,将 a, b, root.val 相加就得到了经过 root 的路径的最大和。对每一个结点都做相同的处理,就得到了全局最大路径和。由此可以定义我们的递归函数 int dfs(TreeNode root),其返回值是以 root 为起点并向下延伸的路径的最大和,dfs(root.left) + dfs(root.right) + root.val 为经过 root 的最大路径和。注意负数值的处理。


    代码实现

    Java

    class Solution {
        private int maxSum;
    
        public int maxPathSum(TreeNode root) {
            maxSum = Integer.MIN_VALUE;
            dfs(root);
            return maxSum;
        }
    
        private int dfs(TreeNode root) {
            if (root == null) {
                return 0;
            }
    
            int leftPathSum = Math.max(dfs(root.left), 0);
            int rightPathSum = Math.max(dfs(root.right), 0);
    
            maxSum = Math.max(maxSum, leftPathSum + rightPathSum + root.val);
          
            return Math.max(leftPathSum, rightPathSum) + root.val;
        }
    }
    
  • 相关阅读:
    flutter添加启动图及设置启动时间
    flutter中通过循环渲染组件
    flutter学习资料汇总
    flutter中显现登录页面成功后跳转的方法
    flutter 常用视图组件
    mpvue学习笔记
    按钮放大动画效果
    一位练习时长两年半的内网渗透练习生
    Kali系统中20个超好用黑客渗透工具,你知道几个?
    渗透测试之三内网跳板
  • 原文地址:https://www.cnblogs.com/mapoos/p/15192029.html
Copyright © 2011-2022 走看看