GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — leetcode/src/BinaryTreeMaxPathSum.java at master · LeBW/leetcode

Expand file tree

/

BinaryTreeMaxPathSum.java

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
33 lines (30 loc) · 1.23 KB
/

BinaryTreeMaxPathSum.java

Copy path

File metadata and controls

33 lines (30 loc) · 1.23 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* 124. Binary Tree Maximum Path Sum
* @author LBW
*/
public class BinaryTreeMaxPathSum {
private int max = Integer.MIN_VALUE; // 用来存储最大路径和
public int maxPathSum(TreeNode root) {
oneSideMax(root); //此时不能直接返回,因为返回值是“一边”的最大和。我们是用全局变量max来存放真正的最大和的。
return max;
}
/**
* 递归,返回的是:当前root以及某一边(左或右)最大的路径和,因此取名为 oneSideMax。
*/
private int oneSideMax(TreeNode root) {
if (root == null) //
return 0;
int left = Math.max(oneSideMax(root.left), 0);
int right = Math.max(oneSideMax(root.right), 0);
if (root.val + left + right > max) // 这一句,是用来测试局部最大值的
max = root.val + left + right;
return Math.max(left, right) + root.val;
}
public static void main(String[] args) {
BinaryTreeMaxPathSum binaryTreeMaxPathSum = new BinaryTreeMaxPathSum();
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
System.out.println(binaryTreeMaxPathSum.maxPathSum(root));
}
}
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.