• 树——binary-tree-maximum-path-sum(二叉树最大路径和)


    问题

      Given a binary tree, find the maximum path sum.

      The path may start and end at any node in the tree.

      For example:
      Given the below binary tree,

             1
            / 
           2   3 

      Return6.

    思路

      用递归方法从叶节点开始,将所求最大路径和maxValue设为全局变量,并赋初始值。

      假设递归到节点n,首先计算左子树的最大路径和left,并与0进行比较,若left<0,则left=0。同理求出右子树最大路径和right。

      将maxValue与left+right+root.val比较,把较大值赋于maxValue。

      递归函数的函数值为节点n.val与左右子树中较大值的和

    代码

     1 /**
     2  * Definition for binary tree
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public int maxValue = Integer.MIN_VALUE;
    12     
    13     public int maxPathSum(TreeNode root) {
    14         if(root==null)
    15             return 0;
    16         max(root);
    17         return maxValue;
    18     }
    19     public int max(TreeNode root){
    20         if(root==null)
    21             return 0;
    22         int left = Math.max(0, max(root.left));
    23         int right = Math.max(0, max(root.right));
    24         maxValue = Math.max(maxValue, left+right+root.val);
    25         return Math.max(left, right)+root.val;
    26     }
    27 }
  • 相关阅读:
    maven上传jar包规范
    java.util.ConcurrentModificationException
    求集合中的最大值和最小值
    对象/集合转换成json
    字符串直接赋值和构造赋值的区别
    CSV文件读取
    读取properties配置文件
    图片轮播 js代码
    工作流数据库字段设计-审批流程。。
    @Html.Partials 加载分布视图传参数
  • 原文地址:https://www.cnblogs.com/jiqianqian/p/7389467.html
Copyright © 2020-2023  润新知