关闭

124. Binary Tree Maximum Path Sum(难)

273人阅读 评论(0) 收藏 举报
分类:

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.

这题跟 

编程之美: 求二叉树中节点的最大距离 很像

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
 class Solution {
 public:
	 int maxPathSum(TreeNode* root) {
		 if (root == NULL) return 0;
		 maxSum = INT_MIN;
		 maxPathDown(root);
		 return maxSum;
	 }

 private:
	 int maxPathDown(TreeNode* root){
		 if (root == NULL) return 0;
		 int left = max(0,maxPathDown(root->left));
		 int right =max(0, maxPathDown(root->right));
		 
		 maxSum = max(maxSum, left + right + root->val);

		 return max(left, right) + root->val;
	 }
	 int maxSum;
 };


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:420542次
    • 积分:8302
    • 等级:
    • 排名:第2572名
    • 原创:390篇
    • 转载:276篇
    • 译文:0篇
    • 评论:30条
    联系方式
    E-mail:gwh_mail@qq.com QQ:1440156051
    最新评论