思路:

后序遍历。

实现:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10  * };
11  */
12 
13 class Solution
14 {
15 public:
16     int dfs(TreeNode* root, int& res)
17     {
18         int l = -1001, r = -1001;
19         if (root->left) l = dfs(root->left, res);
20         if (root->right) r = dfs(root->right, res);
21         res = max(res, max(l, r));
22         int tmp = root->val;
23         if (l > 0) tmp += l;
24         if (r > 0) tmp += r;
25         res = max(res, tmp);
26         return max(max(l, r), 0) + root->val;
27     }
28     int maxPathSum(TreeNode* root)
29     {
30         if (root == NULL) return 0;
31         int res = -1001;
32         dfs(root, res);
33         return res;
34     }
35 };

相关文章:

  • 2021-07-10
  • 2021-06-22
  • 2021-08-08
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-06
猜你喜欢
  • 2021-10-15
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-11
  • 2021-05-13
  • 2021-11-17
相关资源
相似解决方案