[LintCode/LeetCode] Binary Tree Maximum Path Sum

news/2024/7/2 1:21:55

Problem

Given a binary tree, find the maximum path sum.

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

Example

Given the below binary tree:

  1
 / \
2   3

return 6.

Note

调用helper函数更新路径和的最大值res,而helper函数本身需要递归,返回的是单边路径和single。这里需要注意:对于拱形路径和arch,从左子树经过根节点绕到右子树,路径已经确定,就不能再通过根节点向上求和了;对于单边路径和single,只是左边路径和left和右边路径和right的较大值与根节点的和,再与根节点本身相比的较大值,这个值还会递归到上一层继续求和。所以helper函数要返回的是single,主函数中返回的却是最上一层(根节点处)singlearch的较大值,与之前遍历过所有路径的res最大值之间的最大值。

Solution

public class Solution {
    int res = Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) {
        helper(root);
        return res;
    }
    public int helper(TreeNode root) {
        if (root == null) return 0;
        int left = helper(root.left);
        int right = helper(root.right);
        int arch = left+right+root.val;
        int single = Math.max(Math.max(left, right)+root.val, root.val);
        res = Math.max(res, Math.max(single, arch));
        return single;
    }
}

Simplified

public class Solution {
    int res = Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) {
        helper(root);
        return res;
    }
    public int helper(TreeNode root) {
        if (root == null) return 0;
        int left = Math.max(helper(root.left), 0);
        int right = Math.max(helper(root.right), 0);
        res = Math.max(res, root.val + left + right);
        return root.val + Math.max(left, right);
    }
}

http://www.niftyadmin.cn/n/1178041.html

相关文章

00038oracle,Oracle错误一览表

根据Oracle错误码查看对应是什么错误导致的。异常处理概念异常情况处理(EXCEPTION)是用来处理正常执行过程中未预料的事件,程序块的异常处理预定义的错误和自定义错误,由于PL/SQL程序块一旦产生异常而没有指出如何处理时,程序就会自动终止整个程序运行.有三种类型的异常错误&am…

oracle susid,20140228oracle常用语句

查询当前数据名方法一:select name from v$database;方法二:show parameter db方法三:查看参数文件。查询当前数据库实例名方法一:selectinstance_name from v$instance;方法二:show parameter instance方法三:在参数文…

《构建之法》读后感系列之一

忽视了不代表不存在 软件对于计算机学院的我们来说已经不陌生了,课设、作业都是我们练习编程的基本途径,在不断适应这种模式的同时我们也渐渐丧失了自己对“软件”的思考,何为软件?何为工程?从大一时候编的小作业来看&…

2013 Multi-University Training Contest 10 部分解题报告

problem 1001 &#xff08;hdu 4696&#xff09; Answers 题目&#xff1a;http://acm.hdu.edu.cn/showproblem.php?pid4696 思路&#xff1a;在d>0的情况下&#xff0c;当c[]全部为2&#xff0c;且d%21的情况下为NO,否则为yes 1 #include <iostream>2 #include<c…

信息论的熵

1. 前言 熵的概念最早起源于物理学&#xff0c;用于度量一个热力学系统的无序程度。 在信息论里则叫信息量,即熵是对不确定性的度量。从控制论的角度来看&#xff0c;应叫不确定性。信息论的创始人香农在其著作《通信的数学理论》中提出了建立在概率统计模型上的信息度量。他把…

oracle pl/sql编程详细,Oracle PL/SQL 编程基础 实例

create table mytest(name varchar(20),password varchar(30));create or replace procedure sp_pro2 isbegininsert into mytest values(fc,123);end;查看错误信息show error如何调用该过程&#xff1a;1&#xff0c; exec 过程名 (参数&#xff0c;。。)2. call 过程名 (参数…

热部署与热加载

为什么80%的码农都做不了架构师&#xff1f;>>> 1.热部署和热加载的概念 热部署:就是容器状态在运行的情况下重新部署整个项目.在这种情况下一般整个内存会清空,重新加载.简单来说就是Tomcat或者其他的web服务器会帮我们重新加载项目.这种方式可能会造成sessin丢失…