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

binary-tree-maximum-path-sum

时间:2017-06-10 12:38:33      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:namespace   节点   path sum   maximum   nod   path   pat   bin   class   

Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree.

For exmple:
Given the below binary tree,

       1
      /      2   3

Return6.

翻译:给定二叉树,求最大的路径之和,路径的的开始和结束可以为任意节点。

#include "stdafx.h"
#include <iostream>
#include <string>
#include <stdlib.h>
#include <vector>
#include <algorithm>
using namespace std;

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)
        {
            return 0;
        }
        int max_value = -99999999;
        getMaxValue(root, max_value);
        return max_value;
    }
    int getMaxValue(TreeNode *root, int &max_value)
    {
        if (!root)
        {
            return 0;
        }
        int left = max(0, getMaxValue(root->left, max_value));
        int right = max(0, getMaxValue(root->right, max_value));
        max_value = max_value > root->val + left + right ? max_value : root->val + left + right;
        return (left > right ? left : right) + root->val;
    }
};
int main()
{
    TreeNode *tn1 = new TreeNode(3);
    TreeNode *tn2 = new TreeNode(4);
    TreeNode *tn3 = new TreeNode(5);
    TreeNode *tn4 = new TreeNode(6);
    TreeNode *tn5 = new TreeNode(7);
    TreeNode *tn6 = new TreeNode(8);
    tn1->left = tn2;
    tn1->right = tn3;
    tn2->left = tn4;
    tn2->right = tn5;
    tn3->right = tn6;
    Solution so;
    cout << so.maxPathSum(tn1) <<endl;
    return 0;
}

 

binary-tree-maximum-path-sum

标签:namespace   节点   path sum   maximum   nod   path   pat   bin   class   

原文地址:http://www.cnblogs.com/Forever-Road/p/6978110.html

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