本文共 771 字,大约阅读时间需要 2 分钟。
题目描述:
给定一个非空二叉树,返回其最大路径和。
本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。
示例 1:
输入: [1,2,3] 1 / \ 2 3输出: 6
示例 2:
输入: [-10,9,20,null,null,15,7] -10 / \ 9 20 / \ 15 7输出: 42
AC C++ Solution:
解题思路:自下而上更新树的每个节点,返回子树的最大路径和,同时更新max值。代码:
class Solution {public: int maxPathSum(TreeNode* root) { int max = INT_MIN; maxToRoot(root,max); return max; } private: int maxToRoot(TreeNode *root, int &re) { if(!root) return 0; int l = maxToRoot(root->left,re); int r = maxToRoot(root->right,re); if(l < 0) l = 0; if(r < 0) r = 0; if(l+r+root->val > re) re = l + r + root->val; //遍历更新max值 return root->val + max(l,r); //向父节点返回子树的最大路径和 }};
转载地址:http://dgnkb.baihongyu.com/