二叉树中获取从根节点到某个节点的路径

本文探讨了在树搜索过程中使用deque而非stack的原因,deque能够从根节点开始输出,直到找到目标节点,而stack只能进行反向输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个概念大家都懂,直接上代码


bool GetThePathOfNode(BTNode* pRoot, int nData, std::deque<BTNode*>& myDeque)
{
	if (NULL == pRoot)
		return false;

	if (pRoot->nData == nData)
	{
		myDeque.push_back(pRoot);
		return true;
	}

	myDeque.push_back(pRoot);

	if (GetThePathOfNode(pRoot->pLeft, nData, myDeque))
		return true;

	if (GetThePathOfNode(pRoot->pRight, nData, myDeque))
		return true;

	myDeque.pop_back();
	return false;
}

void GetThePathOfNode(BTNode* pRoot, int nData)
{
	if (NULL == pRoot)
	{
		std::cout << "Tree Is Empty!" << std::endl;
		return;
	}

	std::deque<BTNode*> myDeque;
	GetThePathOfNode(pRoot, nData, myDeque);
	
	if (myDeque.empty())
	{
		std::cout << "Not Find The Node!" << std::endl;
		return;
	}

	std::cout << "The Path is : ";
	while (!myDeque.empty())
	{
		std::cout << myDeque.front()->nData << " ";
		myDeque.pop_front();
	}

	std::cout << std::endl;
}

上面中使用std::deque而不使用std::stack,

是因为deque可以从根节点开始输出,到目标节点截止。

而stack却只能从进行反向输出。



二叉树中找到从根节点到特定叶节点的具体路径,你可以采用递归的方式来实现。这里是一个简单的C语言代码示例: ```c #include <stdio.h> #include <stdlib.h> // 定义二叉树结点 typedef struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; } TreeNode; // 创建一个新的树结点 TreeNode* createNode(int val) { TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode)); if (node != NULL) { node->val = val; node->left = NULL; node->right = NULL; } return node; } // 打印路径 void printPath(TreeNode* root, int target, char path[]) { if (root == NULL) return; // 检查是否达到目标节点 if (root->val == target) { printf("%d ", root->val); path[0] = '\0'; puts(path); } else { // 递归左子树 printPath(root->left, target, path + 1); // 如果还没找到,再尝试右子树 if (path[0] != '\0') { path[0] = '|'; // 添加分隔符 printPath(root->right, target, path + 1); } } } int main() { // 以链表形式构建示例树 TreeNode* root = createNode(1); root->left = createNode(2); root->right = createNode(3); root->left->left = createNode(4); root->left->right = createNode(5); // 要查找的目标叶子节点值,假设为5 int target = 5; char path[20]; // 预留空间存放路径字符 path[0] = '\0'; printPath(root, target, path); return 0; } ``` 这个程序首先创建了一个二叉树结构,然后定义了一个`printPath`函数用于沿着从根节点到指定叶节点路径打印节点值。如果找到目标节点,就停止递归并打印路径。如果没有找到,会继续向左右子树递归直到找到目标或遍历完整棵树。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值