二叉树中最大路径和

 

 

 

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

  };

 

posted @ 2020-05-19 20:40  知道了呀~  阅读(263)  评论(0编辑  收藏  举报