Binary Tree Maximum Path Sum
来源:互联网 发布:linux help分段显示 编辑:程序博客网 时间:2024/04/30 09:08
题目原型:
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
.
基本思路:
递归回溯,从总体上来讲,最大路径和是,根节点的值、根节点的值加上左子树最大路径和、根节点的值加上右子树最大路径和,这三者中的最大值。
int max = Integer.MIN_VALUE;public int maxPathSum(TreeNode root){if(root==null)return 0;getMaxPathSum(root);return max;}public int getMaxPathSum(TreeNode root){if(root==null)return 0;int lmax = 0;int rmax = 0;int sum = 0;if(root.left!=null){lmax = getMaxPathSum(root.left);}if(root.right!=null){rmax = getMaxPathSum(root.right);}if(lmax>0)sum+=lmax;if(rmax>0)sum+=rmax;sum+=root.val;//注意最大值是个全局变量,不随递归返回max = max>sum?max:sum;//返回根节点的值、根节点的值加上左子树最大路径和、根节点的值加上右子树最大路径和。三者中最大的值return Math.max(root.val, Math.max(root.val+lmax, root.val+rmax));}
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
- about php.ini
- nyoj_273字母小游戏
- java正则表达式
- java基础_14_正则表达式
- HLSL错误及如何执行龙书中的代码
- Binary Tree Maximum Path Sum
- hdu 2087
- Texture Mapping
- 微软 XMLHttp 使用总结
- poj 2446 (二分图匹配)
- 最简单的Oracle存储过程的编写-初次写存储过程的小白可以看看
- 集训结束
- Java对象序列化
- 使用Java实现人物跑动和放烟花的动画