二叉树最大路径和
1、题目描述
https://leetcode-cn.com/problems/binary-tree-maximum-path-sum/submissions/
2、解题思路:
https://leetcode-cn.com/problems/binary-tree-maximum-path-sum/solution/er-cha-shu-zhong-de-zui-da-lu-jing-he-by-ikaruga/
3、代码:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { int max=Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { dfs(root); return max; } public int dfs(TreeNode root){ if(root==null){ return 0; } // 左右子树的最大路径和是否是正贡献,非正贡献就取0 int leftMax=Math.max(0,dfs(root.left)); int rightMax=Math.max(0,dfs(root.right)); // 判断left->root->right这条路径是不是和最大的 max=Math.max(max,root.val+leftMax+rightMax); // 选一个单边最大的 return root.val+Math.max(leftMax,rightMax); } }
。。