leetcode(三) #112 #113

#112 路径总和

class Solution {
public:
    bool hasPathSum(TreeNode* root, int sum)
	{
		if (root == NULL)
			return false;
		return checker(root, sum);
	}

	bool checker(TreeNode* root, int sum)
	{
		sum -= root->val;
		if (sum == 0 && root->left == NULL&&root->right == NULL)
			return true;
		bool l = false, r = false;
		if (root->left != NULL)
			l = checker(root->left, sum);
		if (root->right != NULL)
			r = checker(root->right, sum);
		return l || r;
	}
};

#113 路径总和II

vector> pathSum(TreeNode* root, int sum) 
	{
		vector> ans;
		if (root == NULL)
			return ans;
		helper(ans, root, vector(), sum);
		return ans;
	}

	void helper(vector>& ans, TreeNode* root, vector arr, int sum)
	{
		sum -= root->val;
		arr.push_back(root->val);
		if (sum == 0 && root->left == NULL&&root->right == NULL)
		{
			ans.push_back(arr);
			return;
		}
		if (root->left != NULL)
			helper(ans, root->left, arr, sum);
		if (root->right != NULL)
			helper(ans, root->right, arr, sum);
	}

 

你可能感兴趣的:(leetcode)