爆米花中底,onemix 玩覓男女款半掌氣墊跑步鞋 89 元
阿新 • • 發佈:2021-12-12
路徑 被定義為一條從樹中任意節點出發,沿父節點-子節點連線,達到任意節點的序列。同一個節點在一條路徑序列中 至多出現一次 。該路徑 至少包含一個 節點,且不一定經過根節點。
路徑和 是路徑中各節點值的總和。
給你一個二叉樹的根節點 root ,返回其 最大路徑和 。
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/binary-tree-maximum-path-sum
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
心之所向,素履以往 生如逆旅,一葦以航class Solution { private Info solve(TreeNode root) { if (root == null) { return new Info(Integer.MIN_VALUE, 0); } Info left = solve(root.left); Info right = solve(root.right); int maxStraightPath = Math.max(root.val, Math.max(left.maxStraightPath, right.maxStraightPath) + root.val); int max = root.val; if (left.maxStraightPath > 0) { max += left.maxStraightPath; } if (right.maxStraightPath > 0) { max += right.maxStraightPath; } max = Math.max(max, Math.max(left.max, right.max)); return new Info(max, maxStraightPath); } public int maxPathSum(TreeNode root) { if (root == null) { return 0; } return solve(root).max; } } class Info { int max; int maxStraightPath; public Info(int max, int maxStraightPath) { this.max = max; this.maxStraightPath = maxStraightPath; } } 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; } }