Easy-understanding JAVA DFS solution


  • 0
    J
    public class Solution {
        public int pathSum(TreeNode root, int sum) {
            if (root == null) {
                return 0;
            }
            
            return findPath(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);
        }
    
        private int findPath(TreeNode root, int sum) {
            if (root == null) {
                return 0;
            }
            
            int res = root.val == sum ? 1 : 0;
            res += findPath(root.left, sum - root.val);
            res += findPath(root.right, sum - root.val);
            return res;
        }
    }
    
    

Log in to reply
 

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