首页 > 代码库 > [leetcode-124-Binary Tree Maximum Path Sum]
[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]
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。