124. Binary Tree Maximum Path Sum

124. Binary Tree Maximum Path Sum

题目

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

For example:
Given the below binary tree,

       1
      / 
     2   3

Return 6. 

解析

  • 这一题有点类似一维数组求最大子序列的和,一维最大子序列和从一维的角度判断,这里二叉树有左右子树考虑。help(root)方法的返回值的意思就是求得root节点到该root子孙的任意一节点的最大路径值(注意区别这里root和根节点root,这里root是递归下去的节点)。在这个函数里还比较了以root为路径节点;

  • 2019.05.13: 这里的最大和路径可以不经过根节点;在递归的时候,需要一个全局变量记录当前结点作为根节点时的最大路径和;然后递归返回的是包含当前结点子树的最大值;

class Solution_124 {

	int sum = INT_MIN;

	int help(TreeNode* root)
	{
		if (!root)
		{
			return 0;
		}
		int left = max(0, help(root->left));   // 已经保证左右子树非负,舍弃掉一些分支;
		int right = max(0, help(root->right));

		sum = max(sum, left + right + root->val); //包括当前节点在路径上的最大值,和不包括当前节点在路径上的最大值,求两者中较大的;

		return max(left, right) + root->val; //返回以当前节点为根的路径最大值;
	}

public:
	int maxPathSum(TreeNode *root) {  //考虑有负节点情况

		if (!root)
		{
			return 0;
		}

		help(root);

		return sum;
	}
};

题目来源

原文地址:https://www.cnblogs.com/ranjiewen/p/8182775.html