把二元查找树转变成排序的双向链表

本文介绍如何将数值序列4, 6, 8, 10, 12, 14, 16转换为双向链表,并通过自定义的二元查找树节点数据结构进行操作。详细步骤包括定义节点结构、树到链表转换函数以及主函数演示。最后,展示转换后的双向链表结构。

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

10
/    \
6      14
/   \      / \
4 8 12 16
转换成双向链表
4=6=8=10=12=14=16。
首先我们定义的二元查找树 节点的数据结构如下:
struct BSTreeNode
{
int m_nValue; // value of node
BSTreeNode *m_pLeft; // left child of node
BSTreeNode *m_pRight; // right child of node

};

// Tree2List.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

typedef struct BSTreeNode
{
	int m_nValue; // value of node
	BSTreeNode *m_pLeft; // left child of node
	BSTreeNode *m_pRight; // right child of node
	BSTreeNode(int nValue)
	{
		m_nValue=nValue;
		m_pLeft=m_pRight=NULL;
	}
	BSTreeNode(struct BSTreeNode* p)
	{
		m_nValue=p->m_nValue;
		m_pLeft=m_pRight=NULL;
	}
	BSTreeNode * AddAfterMe(struct BSTreeNode* p)
	{
		this->m_pRight=p;
		if(p)
			p->m_pLeft=this;
		return p;
	}
} *PBSTreeNode;

PBSTreeNode g_pBSTreeNode=NULL;
PBSTreeNode g_pCurrNode=NULL;
void AddToTail(PBSTreeNode pBSTreeNode,PBSTreeNode pNode)
{
	if(g_pBSTreeNode==NULL)
	{
		g_pBSTreeNode=pNode;
		g_pCurrNode=pNode;
	}
	else
	{
		g_pCurrNode=g_pCurrNode->AddAfterMe(pNode);
	}

}

void Tree2List(BSTreeNode* root)
{
	if(root==NULL)
		return;
	if(root->m_pLeft)
	{
		Tree2List(root->m_pLeft);
	}
	PBSTreeNode pNode=new BSTreeNode(root);
	AddToTail(g_pBSTreeNode,pNode);
	if(root->m_pRight)
	{
		Tree2List(root->m_pRight);
	}

}



int main(int argc, char* argv[])
{
	PBSTreeNode root=new BSTreeNode(10);
	PBSTreeNode L1_1=new BSTreeNode(6);
	PBSTreeNode L1_2=new BSTreeNode(14);
	root->m_pLeft=L1_1;
	root->m_pRight=L1_2;
	PBSTreeNode L2_1=new BSTreeNode(4);
	PBSTreeNode L2_2=new BSTreeNode(8);
	PBSTreeNode L2_3=new BSTreeNode(12);
	PBSTreeNode L2_4=new BSTreeNode(16);
	L1_1->m_pLeft=L2_1;
	L1_1->m_pRight=L2_2;
	L1_2->m_pLeft=L2_3;
	L1_2->m_pRight=L2_4;
////////////////////////////////////
	Tree2List(root);
	//打印链表g_pBSTreeNode
	PBSTreeNode pWalker=g_pBSTreeNode;
	while(pWalker!=NULL)
	{
	printf("%3d",pWalker->m_nValue);
	if(pWalker->m_pRight!=NULL)
		pWalker=pWalker->m_pRight;
	else
		break;
	}
	printf("\n");
	while(pWalker!=NULL)
	{
	printf("%3d",pWalker->m_nValue);
	pWalker=pWalker->m_pLeft;
	}
	printf("\n");
	
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值