Leetcode 124.二叉树中的最大路径和

124.二叉树中的最大路径和

给定一个非空二叉树,返回其最大路径和。

本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。

示例 1:

输入: [1,2,3]

1

/ \

2 3

输出: 6

示例 2:

输入: [-10,9,20,null,null,15,7]

  -10

   / \

  9  20

    /  \

   15   7

输出: 42

 1 class Solution{
 2 public:
 3     int max=INT_MIN;
 4     int dfs(TreeNode* root){
 5         int left_max=root->left?dfs(root->left):0;
 6         int right_max=root->right?dfs(root->right):0;
 7         if(left_max<0) left_max=0;
 8         if(right_max<0) right_max=0;
 9         int temp=left_max+right_max+root->val;
10         if(temp>max){
11             max=temp;
12         }
13         return root->val+(left_max>right_max?left_max:right_max);
14     }
15 
16     int maxPathSum(TreeNode* root){
17         if(root){
18             dfs(root);
19         }else{
20             return 0;
21         }
22         return max;
23     }
24 };

猜你喜欢

转载自www.cnblogs.com/kexinxin/p/10163115.html