二叉树中和为某一值的路径

    题目:输入一棵二叉树和一个整数,打印出二叉树中节点值得和为输入整数的所有路径,从树的根节点开始往下一直到叶子节点所经过的节点形成一条路径。
    解析:每次遍历到叶子节点时,判断当前路径是否等于给定的值。如果是,则存储这条路径到allPath中,如果不是,则遍历下一条路径。
//所有路径集合
vector<vector<int>> allPath;
//某条路径集合
vector<int> path;
vector<vector<int> > FindPath(TreeNode* root,int value)
{
	if(root == NULL)
		return allPath;
	findPath(root,value);
	return allPath;
}

void findPath(TreeNode* root,int value) 
{
	if(root == NULL)
		return;
	if(root->left == NULL && root->right == NULL)
	{
		path.push_back(value);
		if(root->val == value)
		{
			allPath.push_back(path);
		}
	}
	else{
		path.push_back(root->val);
		if(root->left != NULL)
		{
			findPath(root->left,value - root->val);
		}
		if(root->right != NULL)
		{
			findPath(root->right,value - root->val);
		}
	}
	path.pop_back();
}

你可能感兴趣的:(二叉树中和为某一值的路径)