Advertisement
Kame3

Max_Path_Sum_Binary_Tree

May 25th, 2021
862
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.99 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * public class TreeNode {
  4.  *     int val;
  5.  *     TreeNode left;
  6.  *     TreeNode right;
  7.  *     TreeNode() {}
  8.  *     TreeNode(int val) { this.val = val; }
  9.  *     TreeNode(int val, TreeNode left, TreeNode right) {
  10.  *         this.val = val;
  11.  *         this.left = left;
  12.  *         this.right = right;
  13.  *     }
  14.  * }
  15.  */
  16. class Solution {    
  17.     int maxSum = -1001;
  18.     public int maxPathSum(TreeNode root) {
  19.         dfs(root);
  20.        
  21.         return maxSum;
  22.     }
  23.    
  24.     public int dfs(TreeNode root) {
  25.         if (root == null) {
  26.             return 0;
  27.         }
  28.        
  29.         int left = dfs(root.left);
  30.         int right = dfs(root.right);
  31.        
  32.         maxSum = Math.max(maxSum,left+right+root.val);
  33.         maxSum = Math.max(maxSum,root.val);
  34.         maxSum = Math.max(maxSum,root.val + left);
  35.         maxSum = Math.max(maxSum,root.val + right);
  36.        
  37.         return Math.max(Math.max(left,right), 0) + root.val;
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement