求二叉树中和为某个值的路径

#include <iostream>
#include<vector>

using namespace std;


struct BinaryTreeNode
{
	int val;
	BinaryTreeNode* left;
	BinaryTreeNode* right;
};

void FindThePath(BinaryTreeNode* pRoot, int expectedSum, std::vector<int>& path, int currentSum);
//创建一个二叉树结点
BinaryTreeNode* CreateTreeNode(int val)
{
	BinaryTreeNode* pNode = new BinaryTreeNode;
	pNode->val = val;
	pNode->left = nullptr;
	pNode->right = nullptr;
	return pNode;
}
//连接结点
void Connect(BinaryTreeNode* pRoot, BinaryTreeNode* left, BinaryTreeNode* right)
{
	if (pRoot != nullptr)
	{
		pRoot->left = left;
		pRoot->right = right;
	}
}
//释放结点
void DestroyTree(BinaryTreeNode* pRoot)
{
	if (pRoot != nullptr)
	{
		BinaryTreeNode* pLeft = pRoot->left;
		BinaryTreeNode* pRight = pRoot->right;
		delete pRoot;
		pRoot = nullptr;
		DestroyTree(pLeft);
		DestroyTree(pRight);
	}
}
void FindPath(BinaryTreeNode* pRoot, int expectedSum)
{
//判断输入
	if (pRoot == nullptr)
		return;
//保存当前的和
	int currentSum = 0;
	std::vector<int> path;
	FindThePath(pRoot, expectedSum, path, currentSum);
}

void FindThePath(BinaryTreeNode* pRoot, int expectedSum, std::vector<int>& path, int currentSum)
{
	currentSum += pRoot->val;
	path.push_back(pRoot->val);
	bool leaf=false;
//判断是否叶节点
	if (pRoot->left == nullptr&&pRoot->right == nullptr)
		leaf = true;
//当和满足时且为叶节点时打印路径
	if (currentSum == expectedSum && leaf)
	{
		printf("A path is Found:");
		for (auto iter = path.begin();iter != path.end();++iter)
			printf("%d\t", *iter);
		printf("\n");
	}
//继续判断是否递归左子树、右子树
	if (pRoot->left != nullptr)
		FindThePath(pRoot->left, expectedSum, path, currentSum);
	if (pRoot->right != nullptr)
		FindThePath(pRoot->right, expectedSum, path, currentSum);
//最后返回上一层时还要把当前的路径所保存的结点删除
	path.pop_back();
}

int main()
{
	BinaryTreeNode* pNode1 = CreateTreeNode(1);
	BinaryTreeNode* pNode2 = CreateTreeNode(2);
	BinaryTreeNode* pNode3 = CreateTreeNode(3);
	BinaryTreeNode* pNode4 = CreateTreeNode(4);
	BinaryTreeNode* pNode5 = CreateTreeNode(5);
	BinaryTreeNode* pNode6 = CreateTreeNode(6);
	BinaryTreeNode* pNode7 = CreateTreeNode(7);
	BinaryTreeNode* pNode8 = CreateTreeNode(8);
	BinaryTreeNode* pNode9 = CreateTreeNode(9);

	Connect(pNode1, pNode2, pNode3);
	Connect(pNode2, pNode4, pNode5);
	Connect(pNode3, pNode6, pNode7);
	Connect(pNode4, pNode8, pNode9);

	FindPath(pNode1, 10);

	DestroyTree(pNode1);

	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值