Binary Tree Maximum Path Sum
来源:互联网 发布:研究院与研究生院 知乎 编辑:程序博客网 时间:2024/04/29 11:02
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
.
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int maxPathSum(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function int max = 0; int result = maxSum(root, max); return max > result ? max : result; } private: int maxSum(TreeNode *root, int& max_path) { if (root->left == NULL && root->right == NULL) { max_path = root->val; return root->val; } else if (root->right == NULL) { int lmax = 0; int ls = maxSum(root->left, lmax); int sum = root->val + ls; max_path = ls > lmax ? ls : lmax; max_path = max_path > sum ? max_path : sum; return sum > root->val ? sum : root->val; } else if (root->left == NULL) { int rmax = 0; int rs = maxSum(root->right, rmax); int sum = root->val + rs; max_path = rs > rmax ? rs : rmax; max_path = max_path > sum ? max_path : sum; return sum > root->val ? sum : root->val; } else { int lmax = 0, rmax = 0; int ls = maxSum(root->left, lmax); int rs = maxSum(root->right, rmax); int sumr = root->val + rs; int suml = root->val + ls; int sum = root->val + rs + ls; max_path = lmax > rmax ? lmax : rmax; max_path = max_path > rs ? max_path : rs; max_path = max_path > ls ? max_path : ls; max_path = max_path > suml ? max_path : suml; max_path = max_path > sumr ? max_path : sumr; max_path = max_path > sum ? max_path : sum; int max = suml > sumr ? suml : sumr; return max > root->val ? max : root->val; } }};
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Net use 用法
- 业务流程图绘制方法经验谈(上篇)
- JAVA中16种主流数据库的JDBC连接字符串
- 转载:Intel HEX格式 详解
- 算法竞赛入门经典 8.3.2 循环日程表问题
- Binary Tree Maximum Path Sum
- 杭电2734
- C++中获得当前系统时间
- JavaScript:通用的Object属性和方法
- git——简易指南
- Daily-C-Study(16):C语言条件编译#ifdef
- Eclipse调试技巧
- 业务流程图绘制方法经验谈(下篇)
- C++学习推荐图书