BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / acm-icpc / #88439同步于 2015/12/2
该镜像源已超过 30 天没有更新,可能在源站已被删除。
ACM_ICPC机器人发帖

LeetCode的124题 Binary Tree Maximum Path Sum

sun111
2015/12/2镜像同步4 回复
Given a binary tree, find the maximum path sum. For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root. For example: Given the below binary tree, 1 / \ 2 3 Return 6. 下面是LZ的解法,但是超时了 public class Solution { int sum = Integer.MIN_VALUE; int i = 0; public int maxPathSum(TreeNode root) { dfs(root); return sum; } public void dfs(TreeNode root) { if(root == null) return; int value = root.val; if(i == 0) { sum = value; //System.out.println(sum); } else { //System.out.println(value); int max = value > sum + value? value : sum + value; //System.out.println(max); sum = max > sum ? max : sum; //System.out.println(sum); } i++; if(root.left != null) dfs(root.left); if(root.right != null) dfs(root.right); } } 貌似一般的情况都能过,各位大神给点建议。
订阅后,新回复会通过你的通知中心匿名送达。
4 条回复
leo0316机器人#1 · 2015/12/2
楼主的算法是有问题的吧 sum不能保证是连续的路径 正解是:对于以u为根的子树,求出子树节点中到u的最长两条路径。对于每个节点分别计算,求和找最大值就可以。上面两步可以用一个dfs就可以求出。o(N)的复杂度
nuanyangyang机器人#2 · 2015/12/4
节点上的数可以是负的吗?
ahong123机器人#3 · 2015/12/5
dp[p]为从p节点开始的Maximum Path Sum,dp[p]=max(p.val,p.val+max(dp[left],dp[right]) p为父节点,left,right为左右孩子,初始化叶子节点dp[leaf]=leaf.val ,最后遍历每个节点的dp值 取最大的。
stevesun机器人#4 · 2015/12/11
用全局变量记录实际最大和,递归的时候每次返回含当前节点的最大和