Hard-题目32:124. Binary Tree Maximum Path Sum
来源:互联网 发布:腾讯管家mac版 编辑:程序博客网 时间:2024/05/10 19:22
题目原文:
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.
题目大意:
给出一棵二叉树,求出和最大的一条路径。
题目分析:
递归求出每棵子树的最大和,然后分为三种情况:最大和路径在左子树,最大和路径在右子树,最大和路径在根节点,据此更新所有递归过程的最大值即可。
源码:(language:java)
public class Solution { public int max = Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { rec(root); return max; } public int rec(TreeNode root){ if(root == null){ return 0; } int leftSubtreeMaxSum = rec(root.left); // 左子树的最大和 int rightSubtreeMaxSum = rec(root.right); // 右子树的最大和 int arch = leftSubtreeMaxSum + root.val + rightSubtreeMaxSum; int maxPathAcrossRootToParent = Math.max(root.val, Math.max(leftSubtreeMaxSum, rightSubtreeMaxSum)+root.val); max = Math.max(max, Math.max(arch, maxPathAcrossRootToParent)); return maxPathAcrossRootToParent; }}
成绩:
2ms,23.37%,2ms,76.33%
cmershen的碎碎念:
算法实现起来很简单,但有点不易想到。本题还是二叉树递归性质的一种灵活应用,且感觉很贴近面试题。
0 0
- Hard-题目32:124. Binary Tree Maximum Path Sum
- leetcode 124. Binary Tree Maximum Path Sum(Hard)
- Leetcode 124. Binary Tree Maximum Path Sum[hard]
- Leetcode 124. Binary Tree Maximum Path Sum (Hard) (cpp)
- [Leetcode 124, Hard] Binary Tree Maximum Path Sum
- 【Leetcode-Hard-124】Binary Tree Maximum Path Sum
- Tree-----124. Binary Tree Maximum Path Sum
- 124.leetcode Binary Tree Maximum Path Sum(hard)[先序遍历]
- LeetCode 124. Binary Tree Maximum Path Sum
- [LeetCode]*124.Binary Tree Maximum Path Sum
- [Leetcode] 124. Binary Tree Maximum Path Sum
- [leetcode] 124. Binary Tree Maximum Path Sum
- 124. Binary Tree Maximum Path Sum
- [leetcode] 124. Binary Tree Maximum Path Sum
- Leetcode 124. Binary Tree Maximum Path Sum
- Leetcode 124. Binary Tree Maximum Path Sum
- LeetCode 124. Binary Tree Maximum Path Sum
- leetcode 124. Binary Tree Maximum Path Sum
- chrome49浏览器 以上跨域
- Hard-题目31:23. Merge k Sorted Lists
- 将两个两位数的正整数a、b合并形成一个整数放在C中。
- C语言结构体里的成员数组和指针
- java中普通变量、静态变量、静态代码块初始化的顺序辨析
- Hard-题目32:124. Binary Tree Maximum Path Sum
- 通信协议之Http、TCP、UDP详解
- Hard-题目33:97. Interleaving String
- 从键盘上输入一个字符,如果它是小写字母,则把它转换成大写字母输出;否则,直接输出。
- django 基本操作命令
- 嵌入式LED驱动程序(韦东山板子)
- 去掉提示信息
- Hard-题目34:135. Candy
- 自定义View(一):相关知识