求二叉树指定结点到根结点的路径c++ 非常详细。

本文详细介绍了如何在二叉树中查找指定节点并输出从根节点到目标节点的路径,通过实例展示了创建二叉树、递归查找以及展示路径的函数实现。重点在于提供了一个完整的代码实现,适合初学者理解二叉树结构和搜索算法。

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

 看了很多 没有看见完整的代码 我喜欢喂饭喂到嘴边。

部分代码参考16 二叉树:以x为根的子树的深度_DHU杨骅麟(紫外线过敏)的博客-优快云博客

面试经典(16)--二叉树根节点到指定节点的路径_nginux的博客-优快云博客_二叉树根节点到目标节点路径

 运行示例:

 

#include<iostream>
#include<stack>
#include<vector>
using namespace std;
struct Node
{
    string data;
	Node* left;
	Node* right;
};
//查找二叉树指定节点

Node* target = NULL;
void creat(Node*& T, string kk)
{
    string ch;
    cin >> ch;
    if (ch == kk)
    {
        T = NULL;
    }//但凡输入了#号 该节点下一位停止
    else
    {
        T = new Node;
        T->data = ch;
        creat(T->left, kk);
        creat(T->right, kk);
    }
}


void find(Node* root, string x)//用来寻找结点的地址 
{
	Node* p = root;
	if (p == NULL)
	{
		return;
	}
	else if (p->data == x)
	{

		target = p;//核心 找到p的地址 抓包给全局变量 target现在的值就是所求的地址
	}

	else if (p != NULL && p->data != x)
	{
		find(p->left, x);
		find(p->right, x);
	}
}




bool display(Node* pRoot, Node* pNode, vector<string>& v)
{
	if (pRoot == NULL)
	{
		return false;
	}
	v.push_back(pRoot->data);
	bool found = false;
	if (pRoot == pNode)//还是比较指针稳妥,节点值有可能重复
	{
		for (int i = 0; i < v.size(); i++)
			cout << v[i] << " ";
		cout << endl;
		return true;
	}
	if (!found && pRoot->left)
	{
		found = display(pRoot->left, pNode, v);
	}

	//一旦左子树中找到节点,就不需要再遍历右子树
	if (!found && pRoot->right)
	{
		found = display(pRoot->right, pNode, v);
	}
	if (!found)
		v.pop_back();
	return found;
}



int main()
{
	Node* root;
	string kk;
	cout << "请输入表示终止的符号:" << endl;
	cin >> kk;
	cout << "现在请输入你的二叉树 请用先序遍历输入" << endl;
	creat(root, kk);
	vector<string>m;
	cout << "输入你要找的节点" << endl;
	string x;
	cin >> x;	
	find(root, x);
	cout << "路径如下:" << endl;
	display(root, target, m);
	return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杨骅麟(Hadrain Young)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值