LintCode 376: Binary Tree Path Sum

Description:
Given a binary tree, find all paths that sum of the nodes in the path equals to a given number target.


Note:
1.a valid path的定义是 from root node to any of the leaf nodes.所以当满足target条件时还要判断最后一个结点的左右子树是否为空(啊每次都不认真审题要注意啊)
2.注意函数getSum中的sum和path是不加引用,而result是加引用的,因为sum和path在递归中是不共享的,每次更新只作为参数传递下去,而result需要在递归中共享结果。


Code:

class Solution {
	void getSum(TreeNode* root, int target, int sum, vector<int> path, vector<vector<int>>& result) {
		if (!root)
			return;
		if (root->val + sum == target && !root->left && !root->right) {
			path.push_back(root->val);
			result.push_back(path);
			return;
		}
		sum += root->val;
		path.push_back(root->val);
		getSum(root->left, target, sum, path, result);
		getSum(root->right, target, sum, path, result);
		return;
	}
public:
	/**
	* @param root the root of binary tree
	* @param target an integer
	* @return all valid paths
	*/
	vector<vector<int>> binaryTreePathSum(TreeNode *root, int target) {
		// Write your code here
		vector<vector<int>> result;
		vector<int> path;
		int sum = 0;
		getSum(root, target, sum, path,result);
		return result;
	}
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值