面试题34:二叉树中和为某一值的路径

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

题目描述

输入一棵二叉树和一个整数,打印出二叉树中节点值和输入整数的所有路径

定和子集问题,剪枝

void FindPath(BinaryTreeNode *pRoot, int expectedSum)
{
	if(pRoot == nullptr) return;
	vector<int>path;
	int currentSum = 0;
	FindPath(pRoot, expectedSum, path, currentSum);
}

void FindPath(BinaryTreeNode *pRoot, int expectedSum, vector<int>path, int cuurentSum)
{
	currentSum += pRoot->val;
	path.push_back(pRoot->val);
	
	bool isLeaf = pRoot->left == nullptr && pRoot->right == nullptr;
	if(currentSum == expectedSum && isLeaf)
	{
		printf("A path is found:");
		vector<int>::iterator iter = path.begin();
		for(;iter !=path.end();++iter)
			printf("%d\t", *iter);
		print("\n");
	}
	if(pRoot->left != nullptr)
		FindPath(pRoot->left, expectedSum, path, currentSum);
	if(pRoot->right !=nullptr)
		FindPath(pRoot->right, expectedSum, path, currentSum);

	path.pop_back();
	
	
}
发布了68 篇原创文章 · 获赞 2 · 访问量 6178

猜你喜欢

转载自blog.csdn.net/qq_30050175/article/details/90580720