摘要:復雜度思路對于每一節(jié)點,考慮到這一個節(jié)點為止,所能形成的最大值。,是經(jīng)過這個節(jié)點為止的能形成的最大值的一條支路。
Leetcode[124] Binary Tree Maximum Path Sum
DFSGiven 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-childThe path must contain at least one node and does not need
go through the root.
For example: Given the below binary tree,
1 / 2 3Return 6.
復雜度
O(N)
思路
對于每一節(jié)點,考慮到這一個節(jié)點為止,所能形成的最大值。Math.max(left.val, right.val) + root.val,是經(jīng)過這個節(jié)點為止的能形成的最大值的一條支路。
代碼
int sum = Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { if(root == null) return 0; if(root.left == null && root.right == null) return root.val; int left = Math.max(0, maxPathSum(root.left)); int right = Math.max(0, maxPathSum(root.right)); sum = Math.max(sum, left + right + root.val); return Math.max(left, right) + root.val; }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/69815.html
摘要:題目描述舉例題目分析找從任意節(jié)點出發(fā)的任意路徑的最大長度。每個都有可能是其他路徑上的,這種情況要,。每個都有可能作為中心,此時要左側(cè)之前的路徑最長長度,左側(cè)之前的路徑最長長度,此為中心時候的長度將這個分析單元遞歸封裝,即可實現(xiàn)目標。 題目描述: Given a binary tree, find the maximum path sum. For this problem, a p...
摘要:題目要求題目要求從二叉樹中找到任意兩個節(jié)點構(gòu)成的一條路徑,該路徑上節(jié)點的和為最大。其實在這里我們通過遞歸的方法可以發(fā)現(xiàn)以下幾種場景當前節(jié)點作為起始節(jié)點當前節(jié)點不是起始節(jié)點首先我們以當前節(jié)點作為根節(jié)點,找到可能構(gòu)成的最大路徑值。 題目要求 Given a binary tree, find the maximum path sum. For this problem, a path i...
Problem 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 co...
摘要:但是本題的難點在于,使用遞歸實現(xiàn),但是前面的第四種情況不能作為遞歸函數(shù)的返回值,所以我們需要定義兩個值,代表單邊路徑的最大值,用于遞歸用于和回路的較大值。 Binary Tree Maximum Path SumGiven a binary tree, find the maximum path sum. For this problem, a path is defined as a...
摘要:棧迭代復雜度時間空間遞歸??臻g對于二叉樹思路首先我們分析一下對于指定某個節(jié)點為根時,最大的路徑和有可能是哪些情況。代碼連接父節(jié)點的最大路徑是一二四這三種情況的最大值當前節(jié)點的最大路徑是一二三四這四種情況的最大值用當前最大來更新全局最大 Binary Tree Maximum Path Sum Given a binary tree, find the maximum path sum...
閱讀 2991·2021-11-16 11:51
閱讀 2621·2021-09-22 15:02
閱讀 3737·2021-08-04 10:21
閱讀 3627·2019-08-30 15:43
閱讀 1961·2019-08-30 11:04
閱讀 3612·2019-08-29 17:14
閱讀 500·2019-08-29 12:16
閱讀 2945·2019-08-28 18:31