zoukankan      html  css  js  c++  java
  • [leetCode]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 example:
    Given the below binary tree,

           1
          / 
         2   3

    Return 6.

    思想主要是使用递归,获得节点左枝和右枝的最大值,然后和自己的值相加,如果大于最大值则替换。

    同时要注意的是:如果该节点有父节点,那么只能返回self.val+left.val或者self.val+right.val. 

    详细参考:http://www.cnblogs.com/shawnhue/archive/2013/06/08/leetcode_124.html

    C++代码

    /**
     * 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 maxSum;
        bool hasParent;
        Solution(){ maxSum = -999;}
        int maxPathSum(TreeNode *root) {
            maxNodeSum(root,false);
            return maxSum;
        }
    private:
        int maxNodeSum(TreeNode *root, bool hsaParent){
            int leftSum,rightSum,curmax;
            leftSum = rightSum = curmax = 0;
            TreeNode *cur = root;
            if(cur == NULL) return 0;
            if(cur->left != NULL) leftSum = maxNodeSum(cur->left,true);
            if(cur->right != NULL) rightSum = maxNodeSum(cur->right,true);
            if(leftSum < 0)    leftSum = 0;
            if(rightSum < 0) rightSum = 0;
            curmax = cur->val+leftSum+rightSum;
            if(maxSum < curmax) maxSum = curmax;
            if(hasParent) curmax = cur->val + ((leftSum > rightSum)?leftSum : rightSum);        
            return curmax;
        }
    };
    艰难的成长
  • 相关阅读:
    php函数
    2、Locust压力测试 实战
    mysql常用命令
    3、加强siege性能测试
    2、使用siege进行服务端性能测试
    1、siege安装
    京东云Ubuntu下安装mysql
    1、Locust压力测试环境搭建
    1、Monkey环境搭建
    Postman和Selenium IDE开局自带红蓝BUFF属性,就问你要还是不要
  • 原文地址:https://www.cnblogs.com/marylins/p/3584037.html
Copyright © 2011-2022 走看看