Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitc4271e5

Browse files
author
applewjg
committed
Binary Tree Maximum Path Sum
Change-Id: I18d0bd0ddbed9517302aa674bb75c18b478395b1
1 parentca1c5dc commitc4271e5

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

‎BinaryTreeMaximumPathSum.java

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/*
2+
Author: Andy, nkuwjg@gmail.com
3+
Date: Jan 28, 2015
4+
Problem: Binary Tree Maximum Path Sum
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/binary-tree-maximum-path-sum/
7+
Notes:
8+
Given a binary tree, find the maximum path sum.
9+
The path may start and end at any node in the tree.
10+
For example:
11+
Given the below binary tree,
12+
1
13+
/ \
14+
2 3
15+
Return 6.
16+
17+
Solution: Recursion...
18+
*/
19+
20+
/**
21+
* Definition for binary tree
22+
* public class TreeNode {
23+
* int val;
24+
* TreeNode left;
25+
* TreeNode right;
26+
* TreeNode(int x) { val = x; }
27+
* }
28+
*/
29+
publicclassSolution {
30+
publicintmaxPathSum(TreeNoderoot) {
31+
int[]res =newint[1];
32+
res[0] =Integer.MIN_VALUE;
33+
maxPathSumRe(root,res);
34+
returnres[0];
35+
}
36+
intmaxPathSumRe(TreeNoderoot,int[]res) {
37+
if (root ==null)return0;
38+
intleft =maxPathSumRe(root.left,res);
39+
intright =maxPathSumRe(root.right,res);
40+
res[0] =Math.max(res[0],root.val +Math.max(left,0) +Math.max(right,0));
41+
returnMath.max(root.val,root.val +Math.max(left,right));
42+
}
43+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp