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;
        }
    };
    艰难的成长
  • 相关阅读:
    C# 打印多页tif
    页面动态加载js文件
    CPrintDialog 构造函数参数详解
    DEVMODE 结构体
    对C#对象的Shallow、Deep Cloning认识【转】
    PowerShell 启动应用程序【转】
    中文网页的字体
    css3自适应布局单位vw,vh你知道多少?
    微信小程序轮播图宽高计算
    更改wordpress的默认登录页面名称wp-login
  • 原文地址:https://www.cnblogs.com/marylins/p/3584037.html
Copyright © 2011-2022 走看看