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

推荐订阅源

D
Docker
V
V2EX
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
云风的 BLOG
云风的 BLOG
Blog — PlanetScale
Blog — PlanetScale
Recent Announcements
Recent Announcements
Last Week in AI
Last Week in AI
博客园 - Franky
Microsoft Security Blog
Microsoft Security Blog
Hugging Face - Blog
Hugging Face - Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Vercel News
Vercel News
MyScale Blog
MyScale Blog
大猫的无限游戏
大猫的无限游戏
罗磊的独立博客
H
Help Net Security
月光博客
月光博客
Martin Fowler
Martin Fowler
博客园 - 【当耐特】
宝玉的分享
宝玉的分享
P
Proofpoint News Feed
GbyAI
GbyAI
腾讯CDC
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

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

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;
     
    }