LeetCode刷题笔记(树):binary-tree-maximum-path-sum

爱被打了一巴掌 2022-05-25 13:25 274阅读 0赞

  • 转载请注明作者和出处:http://blog.csdn.net/u011475210
  • 代码地址:https://github.com/WordZzzz/Note/tree/master/LeetCode
  • 刷题平台:https://www.nowcoder.com/ta/leetcode
  • 题  库:Leetcode经典编程题
  • 编  者:WordZzzz

    • 题目描述
    • 解题思路
    • C++版代码实现

题目描述

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. 1
  2. / \
  3. 2 3

Return6.

给定一个二叉树,找到最大路径和。 路径可以在树中的任何节点开始和结束。 例如:给定下面的二叉树,
1
/ \
2 3

返回6。

解题思路

递归的思想,先分别计算左右子树的最大值,然后通过比较maxValue和root->val + leftMax + rightMax来确定是否更行maxValue。最后,返回当前root的值加上其左右子树中的最大值,或者0。

C++版代码实现

  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 maxValue = 0;
  13. int maxPathSum(TreeNode *root) {
  14. if(root == NULL)
  15. return 0;
  16. maxValue = -0x7fffff;
  17. getMaxPathSum(root);
  18. return maxValue;
  19. }
  20. int getMaxPathSum(TreeNode *root){
  21. if(root == NULL)
  22. return 0;
  23. int leftMax = max(0, getMaxPathSum(root->left));
  24. int rightMax = max(0, getMaxPathSum(root->right));
  25. maxValue = max(maxValue, root->val + leftMax + rightMax);
  26. return max(0, root->val + max(leftMax, rightMax));
  27. }
  28. };

系列教程持续发布中,欢迎订阅、关注、收藏、评论、点赞哦~~( ̄▽ ̄~)~

完的汪(∪。∪)。。。zzz

发表评论

表情:
评论列表 (有 0 条评论,274人围观)

还没有评论,来说两句吧...

相关阅读

    相关 LeetCode笔记

    [23. Merge k Sorted Lists][] > 要点: > > 1. 学会数据结构PriorityQueue(优先队列)的用法, 通过给优先队列传入自定义