动态规划好巧妙啊啊啊啊啊啊啊 啊
int max =Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { //用动态规划来求解 //DFS //根节点的值、左子树的值、右子树的值、 dfs(root); return max; } private int dfs(TreeNode node) { if(node == null){ return 0; } int left = dfs(node.left); int right = dfs(node.right); int sum = node.val; if(left > 0) sum +=left; if(right > 0) sum += right; max = Math.max(max,sum); return Math.max(left,right)>0?Math.max(left,right)+node.val:node.val; }
——2020.6.24