猫和鱼爪的鸟窝

Pain is in your mind.

【leetcode】Binary Tree Maximum Path Sum

Problem

这里写图片描述

Hint

DFS

Code

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int maxPath(struct TreeNode *root,int *rec){
    if(root==NULL)  return 0;
    int left = maxPath(root->left,rec);
    int right = maxPath(root->right,rec);
    if(left<0)  left = 0;
    if(right<0) right = 0;
    *rec = *rec>left+right+root->val?*rec:left+right+root->val;
    return (left>right?left:right)+root->val;
}
int maxPathSum(struct TreeNode* root) {
    int max = 0x80000000;
    maxPath(root,&max);
    return max;
}

The elegance of algorithm must be tasted by racking your brain. : )

阅读更多
版权声明:Pain is just in your mind. https://blog.csdn.net/yzt33/article/details/46785809
文章标签: algorithm leetcode
个人分类: Algorithm
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

【leetcode】Binary Tree Maximum Path Sum

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭