《原神攻略》2.6版本新增武器及聖遺物屬性介紹
阿新 • • 發佈:2022-03-29
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); } }
。。