二叉树转换为双向链表

根据前序遍历和中序遍历还原构造二叉树
思路:1)开始时双向循环链表为空,第一个节点应该为最左边的节点
            2)中序遍历二叉树,将输出的每个节点加到新创建的双向链表的末尾
#include <iostream>
#include <stack>
using namespace std;


//树的前序遍历
int preOrder1[] = {10, 6, 4, 8, 14, 12, 16};
//树的中序遍历
int inOrder1[] =  {4, 6, 8, 10, 12, 14, 16};


typedef struct Node_
{
	Node_ * left, * right;
	int data;
	bool visit;
}Node;



//重建二叉树
Node * RebuildBTree(Node * & root,int preOrder[], int inOrder[], int n, int pl, int pr, int il, int ir)
{
	int i = 0;

	for (i = il;i <= ir; ++i)
	{
		if (inOrder[i] == preOrder[pl])
		{
			break;
		}
	}
	int k = i - il;
	if (i <= ir)
	{
		root = new Node();
		root->data = inOrder[i];
	}
	else
	{
		root = NULL;
		return root;
	}
	root->left = RebuildBTree(root->left,preOrder, inOrder, k,pl + 1 ,pl + k , il, i-1);
	root->right = RebuildBTree(root->right,preOrder, inOrder, ir - i ,pl + k + 1,pr, i+1, ir);

	return root;
}

//中序遍历树
void ConvertInorder(Node * root, Node * &phead, Node *&pcur)
{
	if (!root)
	{
		return ;
	}

	ConvertInorder(root->left, phead, pcur);
	

	//phead == 0,表示当前链表为空,pcur表示链表末尾节点
	if (phead == 0)
	{
		phead = root;
	}
	else
	{
		pcur->right = root;
	}
	root->left = pcur;
	pcur = root;

	ConvertInorder(root->right, phead, pcur);

}

//打印双向循环链表
void printDoubleList(Node * phead)
{
	if(!phead)
	{
		return;
	}
	Node * pcur = phead;
	while(pcur)
	{
		printf("%d ", pcur->data);
		pcur = pcur->right;
	}

	printf("\n");
}

int main()
{
	Node * ParentRoot = 0;
	Node * ChildRoot = 0;
	int n1 = sizeof(preOrder1) / sizeof(preOrder1[0]);
	ParentRoot = RebuildBTree(ParentRoot,preOrder1, inOrder1, n1, 0, n1-1, 0, n1 - 1);

	//二叉树转为双向链表
	Node * phead = 0;
	Node * pcur = 0;
	ConvertInorder(ParentRoot, phead, pcur);

	printf("\n打印双向链表:");
	printDoubleList(phead);

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值