[leetcode-124-Binary Tree Maximum Path Sum]
Posted hellowOOOrld
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode-124-Binary Tree Maximum Path Sum]相关的知识,希望对你有一定的参考价值。
Given a 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.
For example:
Given the below binary tree,
1
/ \
2 3
Return 6.
思路:
用一个全局变量来记录最大路径和。
对于一个结点,一旦得到他的左子树与右子树的最大路径和,那么也就能得到最终该结点的最大路径和。
递归函数很好理解。如下:
int maxToRoot(TreeNode* root,int &result) { if (root == NULL)return 0; int left = maxToRoot(root->left,result); int right = maxToRoot(root->right, result); if (left < 0)left = 0; if (right < 0)right = 0; if (left + right + root->val > result) result = left + right + root->val; return root->val += max(left,right); } int maxPathSum(TreeNode* root) { int max = -2147483648; maxToRoot(root, max); return max; }
参考:
https://discuss.leetcode.com/topic/5508/simple-o-n-algorithm-with-one-traversal-through-the-tree
以上是关于[leetcode-124-Binary Tree Maximum Path Sum]的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode]*124.Binary Tree Maximum Path Sum
[leetcode-124-Binary Tree Maximum Path Sum]
leetcode -124. Binary Tree Maximum Path Sum
LeetCode124. Binary Tree Maximum Path Sum