码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode-124-Binary Tree Maximum Path Sum]

时间:2017-03-23 16:39:09      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:nod   ret   root   imu   href   roo   bsp   理解   target   

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.

思路:

用一个全局变量来记录最大路径和。

对于一个结点,一旦得到他的左子树与右子树的最大路径和,那么也就能得到最终该结点的最大路径和。

递归函数很好理解。如下:

int maxToRoot(TreeNode* root,int &result)
    {
        if (root == NULL)return 0;
        int left = maxToRoot(root->left,result);
        int right = maxToRoot(root->right, result);
        if (left  < 0)left = 0;
        if (right < 0)right = 0;
        if (left + right + root->val > result) result = left + right + root->val;
        return root->val += max(left,right);
    }
    int maxPathSum(TreeNode* root)
    {
        int max = -2147483648;
        maxToRoot(root, max);
        return max;
    }

参考:

https://discuss.leetcode.com/topic/5508/simple-o-n-algorithm-with-one-traversal-through-the-tree

[leetcode-124-Binary Tree Maximum Path Sum]

标签:nod   ret   root   imu   href   roo   bsp   理解   target   

原文地址:http://www.cnblogs.com/hellowooorld/p/6605357.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!