惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Blog — PlanetScale
Blog — PlanetScale
博客园 - 司徒正美
Vercel News
Vercel News
F
Fortinet All Blogs
月光博客
月光博客
G
Google Developers Blog
博客园 - Franky
GbyAI
GbyAI
The Cloudflare Blog
I
InfoQ
雷峰网
雷峰网
WordPress大学
WordPress大学
罗磊的独立博客
大猫的无限游戏
大猫的无限游戏
T
The Blog of Author Tim Ferriss
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 聂微东
小众软件
小众软件
腾讯CDC
B
Blog
量子位
V
V2EX
S
SegmentFault 最新的问题
Google DeepMind News
Google DeepMind News

博客园 - 来自海边的一片云

CodingTMD’s Reading List De Bruijn 序列生成 Word Ladder I ,II 解题思路 suduko及8皇后问题及相关问题的解题思路 leetcode Word Break II 解题思路 Search for a string in an infinite stream of input string. 内存管理 Permutations leetcode Clone Graph leetcode 开弓没有回头箭 combination sum leetcode Combinations leetcode 组合问题 word break leetcode LRU cache Leetcode 重新试着写blog SQL injection Fuzz testing XML库的解析效率 Init()
Binary Tree Maximum Path Sum 解题注意
来自海边的一片云 · 2014-12-24 · via 博客园 - 来自海边的一片云

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.

解题思路,递归

   a

b      c

curmax = max (a+b, a, a+c) //计算当前节点单边最大值,

如果a+b 最大,那就是说,把左子树包含进来,有利可图

如果a+c 最大,把右子树包含进来,有利可图

如果 a,最大,那就到a为止,最好了。

gmax = max(gmax, max(curmax, a+b+c)) 

这个是看要不要抛弃前面的结果.

void maxpathsumhelper(TreeNode* root, int& currentsum, int& maxsum)
    {
        if(root == NULL)return;
        int leftsum  = 0;
        int rightsum = 0;
        
        maxpathsumhelper(root->left,leftsum, maxsum);
        maxpathsumhelper(root->right,rightsum, maxsum);
        currentsum = max(root->val, max(root->val + leftsum, root->val + rightsum)); //this value will passedback
        maxsum = max(maxsum, max(currentsum, leftsum + rightsum + root->val));
    }
    
    int maxPathSum(TreeNode *root) {
     
     if(root == NULL) return 0;
     int csum = INT_MIN;
     int maxsum = INT_MIN;
     
     maxpathsumhelper(root, csum, maxsum);
     return maxsum;
     
    }