首页 > 代码库 > binary-tree-maximum-path-sum
binary-tree-maximum-path-sum
Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree.
For exmple:
Given the below binary tree,
1 / 2 3
Return6.
翻译:给定二叉树,求最大的路径之和,路径的的开始和结束可以为任意节点。
#include "stdafx.h" #include <iostream> #include <string> #include <stdlib.h> #include <vector> #include <algorithm> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: int maxPathSum(TreeNode *root) { if (!root) { return 0; } int max_value = http://www.mamicode.com/-99999999; getMaxValue(root, max_value); return max_value; } int getMaxValue(TreeNode *root, int &max_value) { if (!root) { return 0; } int left = max(0, getMaxValue(root->left, max_value)); int right = max(0, getMaxValue(root->right, max_value)); max_value = max_value > root->val + left + right ? max_value : root->val + left + right; return (left > right ? left : right) + root->val; } }; int main() { TreeNode *tn1 = new TreeNode(3); TreeNode *tn2 = new TreeNode(4); TreeNode *tn3 = new TreeNode(5); TreeNode *tn4 = new TreeNode(6); TreeNode *tn5 = new TreeNode(7); TreeNode *tn6 = new TreeNode(8); tn1->left = tn2; tn1->right = tn3; tn2->left = tn4; tn2->right = tn5; tn3->right = tn6; Solution so; cout << so.maxPathSum(tn1) <<endl; return 0; }
binary-tree-maximum-path-sum
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。