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

【leetcode】Binary Tree Maximum Path Sum (medium)

时间:2014-11-27 23:24:02      阅读:284      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   for   on   

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

 

找树的最大路径和 注意路径可以从任意点起始和结束。

 

我发现我真的还挺擅长树的题目的,递归不难。就是因为有个需要比较的量(最大和),所以需要再写一个函数。

因为路径可以从任意点起始和结束,所以每次递归的时候左右子树小于等于0的就可以不管了。

#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <stack>
using namespace std;

//Definition for binary tree
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;
        }
        int MaxPathSum = root->val; //赋的初值一定要小于等于最后的值
        maxPathSumCur(root, MaxPathSum);
        return MaxPathSum;
    }
    int maxPathSumCur(TreeNode *root, int& MaxPathSum) {
        if(root == NULL)
        {
            return 0;
        }

        int lsum =  maxPathSumCur(root->left, MaxPathSum);
        int rsum = maxPathSumCur(root->right, MaxPathSum);
        int maxPathSumCurrent = root->val; //每次根的值一定要加上 左右子树的就加大于0的
        if(lsum > 0)
        {
            maxPathSumCurrent += lsum;
        }
        if(rsum > 0)
        {
            maxPathSumCurrent += rsum;
        }
        
        MaxPathSum = max(maxPathSumCurrent, MaxPathSum);
        return max(root->val, max(root->val + lsum, root->val +rsum)); //返回时返回根 节点加左 或右子树 或单独根节点中最大的
    }
    void create(TreeNode *& root)
    {
        int d;
        scanf("%d", &d);
        if(d != 0)
        {
            root = new TreeNode(d);
            create(root->left);
            create(root->right);
        }
    }
};

int main()
{
    Solution s;
    TreeNode * T = NULL;
    s.create(T);
    int sum = s.maxPathSum(T);

    return 0;
}

 

【leetcode】Binary Tree Maximum Path Sum (medium)

标签:style   blog   io   ar   color   os   sp   for   on   

原文地址:http://www.cnblogs.com/dplearning/p/4127392.html

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