JAVA solution by using DFS two times


  • 2
    D
    public class Solution {
        int count = 0;
        public int pathSum(TreeNode root, int sum) {
            if (root != null){
                fun(root,sum);
                pathSum(root.left,sum);
                pathSum(root.right,sum);
            }
            return count;
        }
        public void fun(TreeNode root,int sum){
            if (root != null){
                if (sum - root.val == 0){
                    count++;
                }
                fun(root.left,sum - root.val);
                fun(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.