题目描述:给定非空二叉树,返回其最大路径和。
算法分析:
1、二叉树是递归的,优先考虑递归的思路
2、最大路径和的定义是:从一个叶节点到另一个叶节点所经过的最大路径。二叉树的定义首先是递归的,通过递归,可以方便地遍历树中所有节点;然后定制化需求,更新或输出相应的值即可。这里的需求可以抽象为两点:
- 求所遍历到的节点的最大路径和,更新maxValue值
- 求左右节点到叶节点的相对最大路径中的较大者
class Solution {
int maxValue;
public int maxPathSum(TreeNode root) {
maxValue = Integer.MIN_VALUE;
depth(root);
return maxValue;
}
public int depth(TreeNode node){
if(node == null) return 0;
int left = Math.max(0, depth(node.left));
int right = Math.max(0, depth(node.right));
maxValue = Math.max(maxValue, left+right+node.val);
return Math.max(left, right) + node.val;
}
}