zoukankan      html  css  js  c++  java
  • LeetCode OJ:Binary Tree Maximum Path Sum(二叉树最大路径和)

    Given a binary tree, find the maximum path sum.

    For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root.

    For example:
    Given the below binary tree,

           1
          / 
         2   3

    Return 6.

    求二叉树的最大路径和,感觉好复杂,但是分析一下,由于中间的点不能重叠,所以说肯定一部分在某个点的左边一个在右边。所以可以遍历左右子树来求最大值,相当于遍历所有的单点以及其左右子树之后,不断的更新最大值,用ret全局变量来维护这个最大值。将总体当作根节点加上左边和右边就可以了,代码如下:

     1 class Solution {
     2 public:
     3     int maxPathSum(TreeNode *root) {
     4         if(!root) return ret;
     5         ret = INT_MIN;
     6         dfs(root);
     7         return ret;
     8     }
     9 
    10     int dfs(TreeNode * node)
    11     {
    12         if(node == NULL) return 0;
    13         int val = node->val;
    14         int left = dfs(node->left);
    15         int right = dfs(node->right);
    16         if(left > 0) val += left;
    17         if(right > 0) val += right;
    18         if(val > ret)
    19             ret = val;
    20         return max(node->val, max(node->val + left, node->val + right));
    21     }
    22 private:
    23     int ret;
    24 };
  • 相关阅读:
    Android开发环境搭建
    Noi 2016
    [二分图&最小割]
    [BZOJ 3145][Feyat cup 1.5]Str 解题报告
    [动态图]
    [组合数取模][中国剩余定理]
    [BZOJ 4436][Cerc2015]Kernel Knights
    [NOI 2014]做题记录
    [线段树合并]
    [树套树模板]
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4918464.html
Copyright © 2011-2022 走看看