Simple java solution with comments


  • 0
    D

    /**

    • Definition for a binary tree node.
    • public class TreeNode {
    • int val;
      
    • TreeNode left;
      
    • TreeNode right;
      
    • TreeNode(int x) { val = x; }
      
    • }
      */

    public class Solution {
    public int sumNumbers(TreeNode root) {

        //initialize variable to store the current sum
        int currentSum=0;
        
        //Base case: if root is null, return currentSum
        if(root==null)
            return currentSum;
            
    
        return findPath(root,currentSum);
        
    }
    
    public int findPath(TreeNode root, int currentSum)
    {
        
        
        //Base case: if root is a leaf node, update currentSum and return value
        if(root.left==null && root.right==null)
            return currentSum*10+root.val;
        
        //if left subtree is null, operate on right subtree
        if(root.left==null)
            return findPath(root.right,currentSum*10+root.val);
         
        //if right subtree is null, operate on the left subtree   
        if(root.right==null)
            return findPath(root.left,currentSum*10+root.val);
        
        //if it is an internal node, find sum of left and right subtrees
        return findPath(root.left,currentSum*10+root.val)+findPath(root.right,currentSum*10+root.val);
    }}

Log in to reply
 

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