二叉树中最大路径和

 

 

 

 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));
      }

  };

 

相关文章:

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