【leetcode】437. Path Sum III(easy,DFS深搜)

看代码,深搜
要记得把每个节点当做根节点遍历一次

int pathSumImpl(TreeNode * root, int sum)
{
	if (root == NULL) return 0;
	return (root->val == sum ? 1 : 0) + pathSumImpl(root->left, sum - root->val) + pathSumImpl(root->right, sum - root->val);
}


//437. Path Sum III (DFS深搜)
int Solution::pathSum(TreeNode* root, int sum) 
{
	if (root == NULL) return 0;
	// 每个节点都要当成根节点遍历一次
	return pathSumImpl(root, sum) + pathSum(root->left, sum) + pathSum(root->right, sum);
}

Runtime: 40 ms, faster than 18.90% of C++ online submissions for Path Sum III.
Memory Usage: 14.6 MB, less than 100.00% of C++ online submissions for Path Sum III.

你可能感兴趣的:(leetcode)