Binary Tree Maximum Path Sum
来源:互联网 发布:呼和浩特软件招聘信息 编辑:程序博客网 时间:2024/06/11 04:43
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
.
Solution:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int maxPathSum(TreeNode* root) { int maxSum = root ? root->val : 0; dfs(root, maxSum); return maxSum; } int dfs(TreeNode *root, int &maxSum) { if(!root) return 0; int left = dfs(root->left, maxSum); int right = dfs(root->right, maxSum); maxSum = max(maxSum, root->val + max(left, 0) + max(right, 0)); return root->val + max(max(left, right), 0); }};
0 0
- 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
- 逆序排序的使用练习 1 2 3 4 5 6 逆序成 6 5 4 3 2 1
- python下运行报"SyntaxError: Non-ASCII character '/xe6' "错误解决方法
- 创建优雅表格的8个js工具
- hdu 5025
- 前端精选文摘:BFC 神奇背后的原理
- Binary Tree Maximum Path Sum
- HDU 5014
- PS_变量批量生产名片
- HDU 5012
- UI线程和工作线程
- 懒汉式单例设计模式
- 计算一个字符串中包含另一个字符串的个数
- 移动 IM 学习笔记
- spring常用配置