zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

二叉树 路径
2023-09-27 14:26:30 时间

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

输入 :BinaryTreeNode * root,   int  value;

输出: 和为value的路径上所有值创建二叉树


创建二叉树

class BinaryTreeNode
{
public:
	BinaryTreeNode* left;
	BinaryTreeNode* right;
	int value;
};
//创建二叉树节点
BinaryTreeNode* connectNode(BinaryTreeNode* root, BinaryTreeNode* left, BinaryTreeNode* right)
{
	root->left = left;
	root->right = right;
	return root;
}
//连接二叉树节点
BinaryTreeNode* createNode(int value)
{
	BinaryTreeNode* node = new BinaryTreeNode();
	node->value = value;
	node->left = NULL;
	node->right = NULL;
	return node;
}
实现问题的函数

void FindPath(BinaryTreeNode* root, int expSum, int currentSum, vector<int>path)
{
	path.push_back(root->value);
	currentSum += root->value;
	bool isleaf = (root->left == NULL&&root->right == NULL);
	if (currentSum == expSum&&isleaf == true)
	{
		for (vector<int>::iterator iter = path.begin(); iter != path.end(); iter++)
		{
			cout << *iter << " ";
		}
		cout << endl;
	}
	if (root->left != NULL)FindPath(root->left, expSum, currentSum, path);
	if (root->right != NULL)FindPath(root->right, expSum, currentSum, path);
	path.pop_back();
}
void FindPath(int expSum, BinaryTreeNode* root)
{
	if (root == NULL)return;
	int currentsum = 0;
	vector<int> path;
	FindPath(root,expSum,currentsum,path);
}