zoukankan      html  css  js  c++  java
  • LeetCode OJ-- Binary Tree Maximum Path Sum ***

    https://oj.leetcode.com/problems/binary-tree-maximum-path-sum/

    给一棵二叉树,路径可以从任一点起,到任一点结束,但是可以连成一个路径的。求路径上最大和。

    一般来说,路径是 V 字状的, 递归解的话, 每个点记录它的 左右子树的最大 V 值,并且和其的 V值相比较, 选最大的那个返回。

    同时,为了计算它自己的 V 值,需要保留着,它左子树的 最大 path和,右子树的最大 path 和,这个path指的是 直的,没拐弯的。

    注意,要对路径的值为负数的时候的处理。

    /**
     * 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 maxPathSum(TreeNode *root) {
            if(root == NULL)
                return 0;
            
            int ans = 0;
            calcV(root, ans);
            return ans;
        }
        // return data is the biggest path
        int calcV(TreeNode* root, int &current_biggest_v)
        {
            if(root == NULL)
            {
                current_biggest_v = 0;
                return 0;
            }
            if(root->left == NULL && root->right == NULL)
            {
                current_biggest_v = root->val;
                return root->val;
            }
            int left_biggest_v;
            int right_biggest_v;
            
            int left_path = calcV(root->left, left_biggest_v);
            int right_path = calcV(root->right, right_biggest_v);
            
            int ret_val = 0;
            
            ret_val = max(left_path, right_path);
            ret_val = max(ret_val, 0);
            ret_val = ret_val + root->val;
            
            // with ? statements, with should add bracks
            int current_v = (left_path>0? left_path:0) +( right_path>0? right_path:0) + root->val;
            
            if(root->left && root->right == NULL)
                current_biggest_v = max(left_biggest_v, current_v);
            else if(root->right && root->left == NULL)
                current_biggest_v = max(right_biggest_v, current_v);
            else
            {
                current_biggest_v = max(left_biggest_v, right_biggest_v);
                current_biggest_v = max(current_biggest_v, current_v);
            }
             
            return ret_val;
        }
    };
  • 相关阅读:
    Java编码思想之什么是高内聚低耦合?
    hadoop中block副本的放置策略
    服务器组网的过程
    服务器的类型
    hadoop学习笔记(一):NameNade持久化和DataNode概念
    js中的局部函数和全局函数的调用
    对于javaScript中的alert和document.write()的执行顺序的记录
    常用工具api等链接
    js函数声明外面使用小括号括起来再接一个小括号的写法
    LVS的概念和重要性
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3834728.html
Copyright © 2011-2022 走看看