Binary Tree Maximum Path Sum
来源:互联网 发布:png软件下载 编辑:程序博客网 时间:2024/06/05 01:07
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.
DFS递归。
在后序遍历的时候,求每个点的最大路径sum=本事的val+左子树的和(如果大于0)+右子树的和(如果大于0)。
其中求左右子树的最大和 = max(root->val, max(root->val+lmax, root->val+rmax))
int ans;int dfs(TreeNode *root){ if(root == NULL) return 0; int sum = root->val; int lmax = 0, rmax = 0; if(root->left) lmax = dfs(root->left); if(root->right) rmax = dfs(root->right); if(lmax > 0) sum += lmax; if(rmax > 0) sum += rmax; ans = max(ans, sum); return max(root->val, max(root->val+lmax, root->val+rmax));}int maxPathSum(TreeNode *root){ ans = INT_MIN; dfs(root); return ans;}
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
- H264句法和语法总结(二)
- spring mvc3提高生产力之——利用annotation使前后台数据交互更透明
- 数的计数
- 7 种将字符串反转的 Java 方法
- 心疼自己心疼自己心疼自己
- Binary Tree Maximum Path Sum
- MySQL Enterprise Audit
- 数据抽取工具——DMCTextFilter V4.2(纯文本抽出通用程序库)
- poj 2804 词典 (字典树 或者 快排+二分)
- 那些与鸡缸杯且行且珍惜的人
- hadoop出现ava.lang.ClassNotFoundException: org.codehaus.jackson.map.JsonMappingException
- CUGBACM_Summer_Tranning2【二维线段树】
- IOS-网络请求
- C/C++开发规范之一