leetcode:124. Binary Tree Maximum Path Sum

Given a non-empty 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 must contain at least one node and does not need to go through the root.

Example 1:

Input: [1,2,3]

       1
      / \
     2   3

Output: 6

Example 2:

Input: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7

Output: 42

题目具有一定的迷惑性,有一个大坑就是关于路径的定义,在这里路径的定义一定是一条没有分支的路径,也就是类似于上面的2-1-3是一条路径,但是-10到20到15和5的那一块不是路径,搞清楚这个问题这道题就没什么坑了,接下来就是一系列的深度搜索了。有一个诀窍就是在深度搜索的过程中我们要记录每一步得到的一个结果,因为题目中说了是不需要过root节点的,所以很有可能出现上面15-20-7那样的情况,而这个结果是我们在深度优先搜索中的一个中间结果。搞清楚这两点后这道题基本就做出来了。把情况考虑完全即可。

class Solution {
public:
	int nroot;//用于记录中间结果(最大值)
    int maxPathSum(TreeNode *root) {
    	nroot=root->val;
        int temp=dfs(root);
        return max(nroot,temp);
    }
    int dfs(TreeNode *root){
    	int a=root->val;//是全局深度搜索的结果值
    	int b=a;
    	if(root->left!=NULL)//遍历左子树
    	{
    		int l=dfs(root->left);
    		a=max(a,b+l);//走左边的路径
    		if(root->right!=NULL)
    		{
    			int r=dfs(root->right);
    			a=max(a,b+r);//走右边的路径
    			if(b+r+l>nroot)
    			nroot=b+r+l;//以当前节点并算上两边子树作为一个局部答案的值
			}
		}
    	else if(root->right!=NULL)//加上else,要不然会重复计算
    	{
    		int r=dfs(root->right);
    		a=max(a,b+r);
		}
		nroot=max(nroot,a);//以当前节点走一边(左或右)作为一个局部答案的值
    	return a;
	} 
};

你这么做的时候速度已经快过98%的人了,在看了其他大神的代码后我发现了一种更简洁的写法:


class Solution {
public:
	int nroot;
    int maxPathSum(TreeNode *root) {
    	nroot=root->val;
        int temp=dfs(root);
        return max(nroot,temp);
    }
    int dfs(TreeNode *root){
    	int a=root->val;
    	int b=a;
    	int l=0;//设为0,对结果无影响,毕竟0在自然数域是零元
    	int r=0;
    	if(root->left!=NULL)
    		l=dfs(root->left);
    	if(root->right!=NULL)
    		r=dfs(root->right);
	a=max(b,b+r);
	a=max(a,b+l);
	nroot=max(nroot,b+r+l);
	nroot=max(nroot,a);
    	return a;
	} 
};
思路是一样的,但是会简洁很多。速度也会更快一点。





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值