得到二叉树中从根节点到树中某一节点的路径

这个博客介绍了如何在二叉树中查找指定值的节点并获取从根节点到该节点的路径。提供了前序、中序和后序遍历二叉树的方法,以及查找节点和获取路径的函数。示例代码演示了输入值,输出对应的节点路径。

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

<span style="font-size:14px;">#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;


typedef struct BtNode
{
	int value;
	struct BtNode *lchild;
	struct BtNode *rchild;
}BtNode, *Bitree;

Bitree newBtNode()
{
	Bitree p = new BtNode;

	if( NULL == p )
	{
		cout << "newBtNode func: err -1, NULL==p " << endl;
		return p;
	}

	p->value = 0;
	p->lchild = p->rchild = NULL;
	return p;
}


int createBitree( Bitree *head )
{
	int ret = 0;

	if( NULL == head )
	{
		cout << "createBitree func: err -1, NULL==head" << endl;
		ret = -1;
		return ret;
	}

	int data = 0;
	cin >> data;
	
	if( 0 == data ) // leaf
	{
		*head = NULL;
	}
	else
	{
		*head = newBtNode();
		(*head)->value = data;
		createBitree( &( (*head)->lchild ) );
		createBitree( &( (*head)->rchild ) );
	}


	return ret;
	
}

void preTravel( Bitree head )
{
	if( head != NULL )
	{
		cout << head
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值