Binary Tree Maximum Path Sum(leetcode)

题目:

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

Return 6.

题目来源:https://oj.leetcode.com/problems/binary-tree-maximum-path-sum/

解题思路:用后序遍历进行,想访问左右孩子节点,然后访问根节点,不断更新根节点的val值,不断向上遍历,直到root节点。此时保存的maxResult值就是所求。但是这种方法改变了原来节点的值,如果不能改变原来节点值,则可以考虑用深搜的办法《leetcode题解中给出了答案》

#include<iostream>
using namespace std;

struct TreeNode 
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

void postOrderTraverse(TreeNode *root,int &maxResult)
{
	int leftChildValue=0,rightChildValue=0;
	if(root->left!=NULL)
	{
		postOrderTraverse(root->left,maxResult);
		leftChildValue=root->left->val;
	}
	if(root->right!=NULL)
	{
		postOrderTraverse(root->right,maxResult);
		rightChildValue=root->right->val;
	}
	int sum=root->val;
	if(leftChildValue>0)
		sum+=leftChildValue;
	if(rightChildValue>0)
		sum+=rightChildValue;
	maxResult=max(maxResult,sum);
	root->val+=max(leftChildValue,rightChildValue)>0?max(leftChildValue,rightChildValue):0;	
}

int maxPathSum(TreeNode *root)
{
	if(root==NULL)
		return 0;
	int result=INT_MIN;
	postOrderTraverse(root,result);
	return result;
}

int main()
{
	TreeNode *root=new TreeNode(2);
	root->left=new TreeNode(-1);
//	root->right=new TreeNode(3);
	cout<<maxPathSum(root)<<endl;

	system("pause");
	return 0;
}
《leetcode题解》中用深搜来解这个题,其实这个方法在hihocoder的每周测试中已经用过了。

#include<iostream>
using namespace std;

struct TreeNode 
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

int dfs(TreeNode *root,int &maxResult)
{
	if(root==NULL)
		return 0;
	int l=dfs(root->left,maxResult);
	int r=dfs(root->right,maxResult);
	int sum=root->val;
	if(l>0)
		sum+=l;
	if(r>0)
		sum+=r;
	maxResult=max(maxResult,sum);
	return max(r,l)>0?max(r,l)+root->val:root->val;
}

int maxPathSum(TreeNode *root)
{
	if(root==NULL)
		return 0;
	int result=INT_MIN;
	dfs(root,result);
	return result;
}

int main()
{
	TreeNode *root=new TreeNode(2);
	root->left=new TreeNode(-1);
//	root->right=new TreeNode(3);
	cout<<maxPathSum(root)<<endl;

	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值