最大路径和 java_LeetCode 124. Binary Tree Maximum Path Sum 二叉树中的最大路径和 (C++/Java)...

题目:

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 does not need to go through the root.

Example 1:

Input: [1,2,3]

1

/ \

2 3

Output: 6

Example 2:

Input: [-10,9,20,null,null,15,7]

-10

/ \

9  20

/  \

15   7

Output: 42

分析:

给定一颗二叉树,求其最大路径,路径就是从任意节点出发,到达任意节点的序列,注意路径至少要有一个节点。

这道题和下面两道题做法相同,都是求二叉树的路径问题,可以先回顾下面两个问题。

那么这道题还是从根节点递归求解,当前结点的最大路径,是当前节点的值加上左右孩子的最大路径,同时和全局的最大值进行比较,更新最大值,而作为返回值时,需要在左右孩子中选取最大值加上当前结点的值同时和0比较,选取最大值,因为节点存在负数,那么路径为负数显然是不对的,所以对于值为负数的子树我们向上层返回0即可。

程序:

C++

/**

* Definition for a binary tree node.

* struct TreeNode {

* int val;

* TreeNode *left;

* TreeNode *right;

* TreeNode(int x) : val(x), left(NULL), right(NULL) {}

* };*/

classSolution {public:int maxPathSum(TreeNode*root) {if(root ==nullptr)return 0;int res =INT_MIN;

maxPathSum(root, res);returnres;

}private:int maxPathSum(TreeNode* root, int&res){if(root ==nullptr)return 0;int l = maxPathSum(root->left, res);int r = maxPathSum(root->right, res);int sum = l + r + root->val;

res=max(sum, res);return max(max(l, r) + root->val, 0);

}

};

Java

/*** Definition for a binary tree node.

* public class TreeNode {

* int val;

* TreeNode left;

* TreeNode right;

* TreeNode(int x) { val = x; }

* }*/

classSolution {public intmaxPathSum(TreeNode root) {if(root == null)return 0;

res=Integer.MIN_VALUE;

maxPath(root);returnres;

}private intres;private intmaxPath(TreeNode root) {if(root == null)return 0;int l =maxPath(root.left);int r =maxPath(root.right);int sum = l + r +root.val;

res=Math.max(sum, res);return Math.max(Math.max(l, r) + root.val, 0);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值