Sum root to leaf numbers - Simple Java Solution - 0ms


  • 0
    V

    Using recursion:

    1. Find the number in left subtree
    2. Find the number in right subtree
    3. Sum the above two numbers and return the result
    public class Solution {
        private int sum(TreeNode root, int sum) {
            if( root == null ) return 0;
            sum = (sum*10) + root.val;
            if ( root.left == null && root.right == null ) return sum;
            int lSum = sum(root.left, sum);
            int rSum = sum(root.right, sum);
            return lSum+rSum;
        }
        public int sumNumbers(TreeNode root) {
            if (root==null) return 0;
            return sum(root, 0);
        }
    }
    

Log in to reply
 

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