Neat Java Solution With Comment


  • 3
    S
    public class Solution {
        public int pathSum(TreeNode root, int sum) {
            int count = findPathWithRoot(root, sum);
            if (root != null) count += pathSum(root.left, sum) + pathSum(root.right, sum); //add case when root is excluded.
            return count;
        }
        
        private int findPathWithRoot(TreeNode root, int sum) { //Must contain root.val when calculating sum.
            if (root == null) return 0;
            int count = 0;
            if (root.val == sum) count = 1;
            
            return count + findPathWithRoot(root.left, sum - root.val) + findPathWithRoot(root.right, sum - root.val);
        }
    }
    

Log in to reply
 

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