124. Binary Tree Maximum Path Sum
问题描述:
Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
Example 1:
Input: [1,2,3] 1 / \ 2 3 Output: 6
Example 2:
Input: [-10,9,20,null,null,15,7] -10 / \ 9 20 / \ 15 7 Output: 42
解题思路:
找到书中相邻节点最大的和。
首先我们先观察那种可以组成和:
1. 左节点->根节点<-右节点
2.左节点->根节点
3.根节点<-右节点
4.根节点
注意的是:
若我们根节点连接左子树中的最大的和,即通过左孩子连到根节点,那么代表左子树中不能将左右节点通过根节点连起来。
所以我们在遍历树时,返回以该节点为根的子树返回的不连接左右子节点的最大值。
但是也可能我们要求的最大值存在与该节点连接其左右子树。
所以我们要进行比较
又做一遍之后发现之前的代码不够简洁,现在更新一下~
代码:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int maxPathSum(TreeNode* root) { int maxV = INT_MIN; pathValue(root, maxV); return maxV; } private: int pathValue(TreeNode* root, int &maxV){ //we calculate the largest Value which pass root if(!root) return 0; int leftV = pathValue(root->left, maxV); int rightV = pathValue(root->right, maxV); //calculate the subMax int subMax = max(root->val, leftV + root->val); subMax = max(subMax, rightV + root->val); maxV = max(subMax, maxV); maxV = max(maxV, leftV + root->val + rightV); return subMax; } };