Find the maximum sum path in binary tree


  • 0
    M

    Find the maximum sum path in binary tree

    e.g.

                8
    
        1             2            => 22
    
     5          6 
      
    
                                 10
    
                         -3
      
                -5                10
     
            7                4            10         => 31
    
    

  • 1
    U

    @mohan.s.upadhyay why the 2nd tree is 31? I think it will be 33?


  • 0
    D

    I guess I understood the question.

    
    
    class TreeNode {
    	int val;
    	 public TreeNode(){
    		 val=0;
    	 }
    	 public TreeNode(int a){
    		 val=a;
    	 }
    	 TreeNode left;
    	 TreeNode right;
    }
    public class maxSum {
    	
    	public static int hasPathSum(TreeNode root, int sum) {
    		   if(root == null){
    		     return sum;
    		   }
    		   if(root.left == null && root.right == null){
    		      return (root.val + sum);
    		   }
    		   return Math.max(hasPathSum(root.left, sum + root.val), hasPathSum(root.right, sum + root.val));
    		   	   
    		}
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		
    		TreeNode t1= new TreeNode();
    		t1.val=3;
    		t1.left=new TreeNode(5);
    		t1.right=new TreeNode(8);
           System.out.println(hasPathSum(t1,0));
    	}
    
    }
    
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.