Binary Tree Maximum Path Sum
124. Binary Tree Maximum Path Sum
题目链接:https://leetcode.com/problems/binary-tree-maximum-path-sum/#/description
题目大意:给定一棵二叉树,查找该二叉树的最大路径和。路径的定义是,从某个结点出发,沿着父子连接达到任意结点时经过的结点序列。路径至少包含一个结点,但不要求一定要经过根结点。
思路:对于根节点为root的树,以根节点为端点的最大路径和maxEndRoot(root)=max(root->val, maxEndRoot(root->left) + root->val, maxEndRoot(root->right) + root->val),不要求经过根结点的最大路径和maxPath(root) = max(maxPath(root->left), maxPath(root->right), maxEndRoot(root), maxEndRoot(root->left) + root->val + maxEndRoot(root->right))。
算法复杂度分析:时间复杂度O(n),空间复杂度O(log(n))。
代码:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 int maxPathSum(TreeNode* root) { 13 int maxSum = root->val; 14 recurMaxSum(root, maxSum); 15 return maxSum; 16 } 17 private: 18 int recurMaxSum(TreeNode *root, int &maxSum) { 19 if (!root) 20 return 0; 21 int sum = root->val; 22 int leftSum = recurMaxSum(root->left, maxSum); 23 sum += leftSum > 0 ? leftSum : 0; 24 int rightSum = recurMaxSum(root->right, maxSum); 25 sum += rightSum > 0 ? rightSum : 0; 26 maxSum = max(maxSum, sum); 27 return max(root->val, max(leftSum + root->val, rightSum + root->val)); 28 } 29 };
评测系统上运行结果: