zoukankan      html  css  js  c++  java
  • binary-tree-maximum-path-sum

    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;
    }
    既然选择了远方,便只顾风雨兼程
  • 相关阅读:
    数据访问层之Repository
    IIS执行原理
    异常分析
    Logger
    JSTL
    Kubernetes
    NET Core WordPress
    net平台的rabbitmq
    MySQL can’t specify target table for update in FROM clause
    EqualsBuilder和HashCodeBuilder
  • 原文地址:https://www.cnblogs.com/Forever-Road/p/6978110.html
Copyright © 2011-2022 走看看