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;
        }
    };
    艰难的成长
  • 相关阅读:
    mysql对库,表,数据类型的操作以及完整性约束
    mysql数据库初步了解
    响应式及Bootstrap
    事件流丶事件对象
    JQuery初识(三 )
    JQuery初识(二)
    JQuery初识
    sencha touch tpl 实现按钮功能
    sencha touch 分享到微博扩展
    sencha touch 隐藏滚动条样式的几种方式
  • 原文地址:https://www.cnblogs.com/marylins/p/3584037.html
Copyright © 2011-2022 走看看