Java 26ms DFS


  • 0
    M

    The idea is just running DFS from each node and add up all results.

    public class Solution {
        private int dfsCnt(TreeNode node, int remain) {
            int tmp = 0;
            if (node.left != null)
                tmp += dfsCnt(node.left, remain-node.val);
            if (node.right != null)
                tmp += dfsCnt(node.right, remain-node.val);
            if (remain==node.val)
                tmp++;
            return tmp;
        }
        
        public int pathSum(TreeNode root, int sum) {
            if (root == null)
                return 0;
            int res = 0;
            res += dfsCnt(root, sum);
            res += pathSum(root.left, sum);
            res += pathSum(root.right, sum);
            return res;
        }
    }
    

Log in to reply
 

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