leetcode-cn Daily Challenge on June 21, 2020
Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
Input: [1,2,3] 1 / \ 2 3 Output: 6
Input: [-10,9,20,null,null,15,7] -10 / \ 9 20 / \ 15 7 Output: 42
- mine
- Java
- DFS
Runtime: 0 ms, faster than 100.00%, Memory Usage: 41.1 MB, less than 88.47% of Java online submissions
// O(N)time O(D)space // N = node.size // D = root's depth public int res = Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { dfs(root); return res; } public int dfs(TreeNode node){ if(node == null){ return 0; } int left = Math.max(dfs(node.left), 0); int right = Math.max(dfs(node.right), 0); int count = left + right + node.val; res = Math.max(res, count); return node.val + Math.max(right, left); }
- DFS
- Java