首页 > 其他 > 详细

二叉树中最大路径和

时间:2020-05-19 21:44:09      阅读:61      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

 

 

 class Solution {
  public:
      int result;

      int maxPathSum(TreeNode* root) {
          if (!root) return 0;
          result = root->val;
          dfs(root);
          return result;
      }
      //dfs递归求解以root为根节点的子树的和
      int dfs(TreeNode* root) {
          if (!root) return 0;
          int left = max(dfs(root->left), 0);
          int right = max(dfs(root->right), 0);
          result = max(root->val + left + right, result);
          return root->val + max(0, max(left, right));
      }

  };

 

二叉树中最大路径和

原文:https://www.cnblogs.com/-citywall123/p/12919398.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!