Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1
/ \
2 3
Return 6.
后序遍历!
1 /** 2 * Definition for binary tree 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 myMax(int a, int b, int c) { 13 a = a > b ? a : b; 14 return a > c ? a : c; 15 } 16 17 int getMaxSum(TreeNode *root, int &max_sum) { 18 if (root == NULL) { 19 return 0; 20 } 21 int local_max = root->val; 22 int left = getMaxSum(root->left, max_sum); 23 int right = getMaxSum(root->right, max_sum); 24 local_max += (left > 0) ? left : 0; 25 local_max += (right > 0) ? right : 0; 26 max_sum = max_sum > local_max ? max_sum : local_max; 27 return myMax(root->val, root->val + left, root->val + right); 28 } 29 30 int maxPathSum(TreeNode *root) { 31 int max_sum = INT_MIN; 32 getMaxSum(root, max_sum); 33 return max_sum; 34 } 35 };
本文介绍了一种求解二叉树中最大路径和的算法实现。通过后序遍历的方法,递归地计算每个节点的最大贡献值,并更新全局最大路径和。此算法能够有效地找到从任意节点开始和结束的最大路径。
532

被折叠的 条评论
为什么被折叠?



