标签:
binary-tree-maximum-path-sum
题目描述
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
Return6.
思路
5
/ \
3 8
/ \ / \
2 4 6 9
/ \ \
1 7 10
每个节点对应的值为
32
/ \
7 27
/ \ / \
3 4 13 19
/ \ \
1 7 10
代码
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int sum = 0x80000000; // 赋值为最小值
public int maxPathSum(TreeNode root) {
if (root == null) {
return 0;
}
getSum(root);
return sum;
}
public int getSum(TreeNode root) {
if (root == null) {
// 没有节点,返回0
return 0;
}
// 后序遍历
int leftNum = getSum(root.left);
int rightNum = getSum(root.right);
// 判断子节点的值是否小于0
if (leftNum < 0) {
leftNum = 0;
}
if (rightNum < 0) {
rightNum = 0;
}
// 计算当前路径值,和现有sum比较
int temp = leftNum + rightNum + root.val;
if (temp > sum) {
sum = temp;
}
// 返回左右子节点中值比较大的一个
return (leftNum > rightNum ? leftNum : rightNum) + root.val;
}
}
binary-tree-maximum-path-sum-LeetCode
标签:
原文地址:http://www.cnblogs.com/rosending/p/5769105.html