数组和链式二叉树之间的转换,你知道吗?

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lingling_nice/article/details/80972650

二叉树的顺序存储结构

            用一维数组存储二叉树中的结点,并且结点的存储位置,也就是数组的下标要能体现结点之间的逻辑关系

已知双亲结点为i

              左孩子的结点为(2i+1),右孩子的结点为(2i+2)

已知孩子结点为i

             双亲结点为:(i-1)/2

#include<iostream>
using namespace std;
typedef char ElemType;  
#define END '#'

typedef struct  BtNode
{
	BtNode *leftchild;
	BtNode *rightchild;
	ElemType data;
}BtNode,*BinaryTree;
//购买结点
BtNode *Buynode()
{
	BtNode *p=(BtNode *)malloc(sizeof(BtNode));
	if(NULL==p)  exit(1);
	memset(p,0,sizeof(BtNode));
	return p;

}
void *Freenode(BtNode *ptr)
{
	free(ptr);
}

1.根据已存在的链式二叉树转为顺序存储(数组)形式的二叉树结构

void CreateTree_br(BtNode* node, ElemType* br, int len, int pos)//根据链式二叉树建立数组形式的二叉树
{
	if (node == NULL || br == NULL || len<1)        //pos:在数组中的下标位置
	{
		return;
	}
	br[pos] = node->data;
	if (pos*2+1<len)
	{
		CreateTree_br(node->leftchild, br, len, pos * 2 + 1);
	}
	if (pos * 2 + 2<len)
	{
		CreateTree_br(node->rightchild, br, len, pos * 2 + 2);
	}
}

2.根据已存在的顺序存储(数组)形式的二叉树结构转为链式二叉树

BtNode* Create_tree(ElemType *ar, int n,int pos)//int
{
	
	if (ar!=NULL&&pos<n)
	{
		BtNode* s = Buynode();
		s->data = ar[pos];
		s->leftchild = Create_tree(ar, n, pos * 2 + 1);
		s->rightchild = Create_tree(ar, n, pos * 2 + 2);
		return s;
	}
	return NULL;
}

3.根据数组存储,中序遍历的方法

//通过数组存储,中序遍历
void InArorder(ElemType *ar,int i,int n)
{
	if(i<n)
	{
		InArorder(ar,2i+1,n);
		cout<<ar[i]<<"  ";
		InArorder(ar,2i+2,n);

	}
}

猜你喜欢

转载自blog.csdn.net/lingling_nice/article/details/80972650