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.

    参考资料:

      1. http://www.cnblogs.com/shawnhue/archive/2013/06/08/leetcode_124.html

      2. http://www.cnblogs.com/x1957/p/3275854.html

     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     int ans;
    13     int scanT(TreeNode* root){
    14         if(root == NULL) return 0;
    15         int left = scanT(root -> left);
    16         int right = scanT(root -> right);
    17         int val = root -> val;
    18         if(left > 0) val += left;
    19         if(right > 0) val += right;
    20         if(val > ans) ans = val;
    21         return max(root->val ,max(left +  root -> val , right + root -> val));
    22     }
    23     int maxPathSum(TreeNode *root) {
    24         // Start typing your C/C++ solution below
    25         // DO NOT write int main() function
    26         if(root == NULL) return 0;
    27         ans = root -> val;
    28         scanT(root);
    29         return ans;
    30     }
    31 };
  • 相关阅读:
    LINNX联网配置文件
    linux文件系统配置文件
    linux引导和登录/注销配置文件
    LINUX访问文件配置
    LINUX配置文件介绍
    tcpdump的表达式介绍
    tcpdump命令介绍
    DNS客户端配置文件/etc/resolv.conf
    tcpdump概述
    LINUX普通猫的拔号工具介绍
  • 原文地址:https://www.cnblogs.com/vincently/p/4231670.html
Copyright © 2011-2022 走看看