[关闭]
@snuffles 2019-04-04T17:07:25.000000Z 字数 390 阅读 930

L124 二叉树中的最大路径和


给定一个非空二叉树,返回其最大路径和。
本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。

解:递归思想,找出左右的路径哪个和大(正数),返回max(left,right)+root->val

  1. int res = INT_MIN;
  2. int maxPathSum(TreeNode* root) {
  3. getMax(root);
  4. return res;
  5. }
  6. int getMax(TreeNode *root){
  7. if(root == NULL) return 0;
  8. int left = max(0,getMax(root->left));
  9. int right = max(0,getMax(root->right));
  10. res = max(res, root->val+left+right);
  11. return max(left,right)+root->val;
  12. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注