leetcode124】的更多相关文章

题目: 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. 解题思路: 最长路径和要分几种情况考虑,对于这样一个节点 cur / \ left right 设left是左子树的最长路径和,right是右子树的最长路径和,要求当前…
Given a non-empty 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 must contain at least one node and doe…
(没做出来,典型题目重要) 二叉树中的最大路径和(hard) 给定一个非空二叉树,返回其最大路径和. 本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列.该路径至少包含一个节点,且不一定经过根节点. 示例 1: 输入: [1,2,3] 1 / \ 2 3 输出: 6 示例 2: 输入: [-10,9,20,null,null,15,7]   -10    / \   9  20     /  \    15   7 输出: 42 关键点:1.和求根节点到叶节点的最长路径的题目一样(最…
class Solution { int maxValue; public int maxPathSum(TreeNode root) { maxValue = Integer.MIN_VALUE; maxPathDown(root); return maxValue; } private int maxPathDown(TreeNode node) { if (node == null) return 0; int left = Math.max(0, maxPathDown(node.lef…
给定一个非空二叉树,返回其最大路径和. 本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列.该路径至少包含一个节点,且不一定经过根节点. 示例 1: 输入: [1,2,3] 1 / \ 2 3 输出: 6 示例 2: 输入: [-10,9,20,null,null,15,7] -10 / \ 9 20 / \ 15 7 输出: 42 /** * Definition for a binary tree node. * public class TreeNode { * int val…
第一选择是将其转化成图用动态规划,但这样还是太麻烦 使用递归的思路,对于当前的节点root,分别求左右孩子到当前节点的单项路径权值最大的路径权值,然后记包含当前节点的路径权值为 path_price=root->val+left_gain+right_gain,取sum_max和他较大的: 返回左右孩子权值最大的单向路径(只往上不拐弯)的权值(这需要好好理解,因为更新权值的式子是root->val+left_gain+right_gain,即从左子路到根再到右子路的一条式子,所以计算left_…
C++版 数组和字符串 正文 链表: 正文 树与图: 树: leetcode236. 二叉树的最近公共祖先 递归(先序) leetcode124二叉树最大路径和 递归 图: leetcode 547朋友圈(DFS,并查集) leetcode 207课程表(拓扑排序) leetcode 315 计算右侧小于当前元素的个数 (归并排序.树状数组(BIT),线段树,二叉搜索数(BST)) 回溯算法: leetcode 131分割回文串(回溯.分治.DFS.动态规划) 排序和搜索: leetcode37…
给定一个非空二叉树,返回其最大路径和. 本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列.该路径至少包含一个节点,且不需要经过根节点. 示例 1: 输入: [1,2,3] 1 / \ 2 3 输出: 6 示例 2: 输入: [-10,9,20,null,null,15,7]   -10    / \   9  20     /  \    15   7 输出: 42 这道题目的思路是深度优先搜索,每个节点当前的值加上左子树里最大单路径值加上右子树最大单路径值,就是此节点的最大路径和…