Binary Tree Maximum Path Sum leetcode
来源:互联网 发布:linux eth0配置ip 编辑:程序博客网 时间:2024/04/28 09:27
Given a binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root.
For example:
Given the below binary tree,
1 / \ 2 3
Return 6
.
给出一棵二叉树,寻找一条路径使其路径和最大,路径可以在任一节点中开始和结束(路径和为两个节点之间所在路径上的节点权值之和)
要找到二叉树种任意一点到任意一点相加的最大值,分三种情况,
一种是从跟节点左侧的某个点走到跟节点右侧某个点,
第二种是从跟节点左侧的某个点走到跟节点左侧的某个点,
第三种是从跟节点右侧的某个点到跟节点右侧的某个点。
current只是当前值和左侧最大和右侧最大的三者的比较,culculateSum这个函数的功能是递归求出某个点的左侧路径和右侧路径和自身值的三者的最大值,
max[0]记录某个点左侧路径、右侧路径、自身、左侧加右侧加自身 四者之间的最大值。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public int maxPathSum(TreeNode root) { int max[] = new int [1]; max[0] = Integer.MIN_VALUE; culculateSum(root, max); return max[0]; } public int culculateSum(TreeNode root, int[] max) { if (root == null) { return 0; } int left = culculateSum(root.left, max); int right = culculateSum(root.right, max); int current = Math.max(root.val, Math.max(root.val + left, root.val + right)); max[0] = Math.max(max[0], Math.max(current, left + root.val + right)); return current; }}
0 0
- *****(leetcode) Binary Tree Maximum Path Sum (tree)
- LeetCode Binary Tree Maximum Path Sum
- [Leetcode] Binary Tree Maximum Path Sum
- [leetcode] Binary Tree Maximum Path Sum
- LeetCode Binary Tree Maximum Path Sum
- [LeetCode] Binary Tree Maximum Path Sum
- leetcode Binary Tree Maximum Path Sum
- 【leetcode】Binary Tree Maximum Path Sum
- LeetCode - Binary Tree Maximum Path Sum
- [LeetCode]Binary Tree Maximum Path Sum
- [Leetcode]Binary Tree Maximum Path Sum
- Leetcode: Binary Tree Maximum Path Sum
- LeetCode-Binary Tree Maximum Path Sum
- [leetcode] Binary Tree Maximum Path Sum
- LeetCode - Binary Tree Maximum Path Sum
- LeetCode 124: Binary Tree Maximum Path Sum
- 【Leetcode】Binary Tree Maximum Path Sum
- LeetCode | Binary Tree Maximum Path Sum
- 关于JMeter的CSV Data Set Config的源码改写(包括了部分界面等代码的分析)
- 函数(方法)与数组
- 二叉树的几种遍历方法
- 底部菜单实现(一):button和fragment
- ssh 免密码登录
- Binary Tree Maximum Path Sum leetcode
- Apple 开发者账号申请注册 类型区分 一分钟掌握苹果开发者计划教程
- jquery获取checkbox选中的值并追加到input中
- 负载均衡
- tomcat配置集群
- C#编程之委托与事件(二)
- JSP——第2章: JSP语法基础
- IOS开发——旋转(CGAffineTransformMakeRotation)之后view和子view坐标系的变化
- Android实现系统ROOT, 并能赋予app root权限