zoukankan      html  css  js  c++  java
  • lintcode-94-二叉树中的最大路径和

    94-二叉树中的最大路径和

    给出一棵二叉树,寻找一条路径使其路径和最大,路径可以在任一节点中开始和结束(路径和为两个节点之间所在路径上的节点权值之和)

    样例

    给出一棵二叉树:

    返回 6

    标签

    动态规划 分治法 递归

    思路

    找出某节点最大和次大路径,合并这两条路径即为最大路径和。

    code

    /**
     * Definition of TreeNode:
     * class TreeNode {
     * public:
     *     int val;
     *     TreeNode *left, *right;
     *     TreeNode(int val) {
     *         this->val = val;
     *         this->left = this->right = NULL;
     *     }
     * }
     */
    class Solution {
    public:
        /**
         * @param root: The root of binary tree.
         * @return: An integer
         */
        int maxPathSum(TreeNode *root) {
            int maxSum = 0x80000000;
            findMaxSum(root, maxSum);
            return maxSum;
        }
    
        int findMaxSum(TreeNode *root, int &curMax) {
            // write your code here
            int maxLeft = 0, maxRight = 0, maxValue = 0;
    
            if(root == NULL) {
                return 0;
            }
    
            maxLeft = findMaxSum(root->left, curMax);
            maxRight = findMaxSum(root->right, curMax);
    
            int temp = (0>maxLeft?0:maxLeft) + (0>maxRight?0:maxRight) + root->val;
            curMax = curMax > temp ? curMax : temp;
    
    
            return ( 0>(maxRight>maxLeft?maxRight:maxLeft) ? 0 : (maxRight>maxLeft?maxRight:maxLeft) ) + root->val;
        }
    };
    
  • 相关阅读:
    深入理解Http协议
    Http协议详解
    过滤器、监听器、拦截器的区别
    HTTP状态代码集
    理解XML-RPC
    Axis2 解析
    REST SOAP XML-RPC分析比较
    Spring 第一天课程
    Spring 框架学习 有用
    数据库主从复制,读写分离,负载均衡,分表分库的概念 没用
  • 原文地址:https://www.cnblogs.com/libaoquan/p/7150892.html
Copyright © 2011-2022 走看看