• 二叉树与数组


    1.将二叉树转换为顺序存储结构,按完全二叉树形式存储,无元素的结点当做虚结点。按层次顺序遍历二叉树,设根结点编号为0,设置一队列,将结点及其序号入队。出队时将结点及其编号写入顺序存储结构。

    #include "stdafx.h"
    #include<iostream>
    using namespace std;
    typedef struct BTreeNode
    {
    	int data;
    	struct BTreeNode *lchild,*rchild;
    }BTree;
    int _tmain(int argc, _TCHAR* argv[])
    {
    	return 0;
    }
    typedef struct{
    	BTree *node;
    	int num;
    }tnode;
    void BTreeToSeqt(BTree *t,char s[])
    {
    	tnode q[100];
    	tnode tq;
    	int front=0,rear=0;
    	BTree *p;
    	if(t==NULL)exit(0);
    	for(int i=0;i<100;i++)
    	{
    		s[i]='#';//虚结点
    		tq.node=t;tq.num=1;q[++rear]=tq;//根结点入队
    		while(front<rear)//存入顺序存储结构
    		{
    			tq=q[++front];
    			p=tq.node;
    			i=tq.num;
    			s[i]=p->data;
    			if(p->lchild)//左子女入队
    			{
    				tq.node=p->lchild;
    				tq.num=2*i;
    				q[++rear]=tq;
    			}
    			if(p->rchild)//右子女入队
    			{
    				tq.node=p->rchild;
    				tq.num=2*i+1;
    				q[++rear]=tq;
    			}
    		}
    	}
    }
    

     2.顺序结构建立二叉树,有些结点是虚结点

    #include "stdafx.h"
    #include<iostream>
    using namespace std;
    typedef struct BTreeNode
    {
    	int data;
    	struct BTreeNode *lchild,*rchild;
    }BTree;
    int _tmain(int argc, _TCHAR* argv[])
    {
    	return 0;
    }
    typedef struct{
    	BTree *node;
    	int num;
    }tnode;
    void create(BTree *t,char s[],int length)//length为二叉树数组长度
    {
    	tnode q[100];
    	tnode tq;
    	int front=0,rear=0;
    	t=(BTree*)malloc(sizeof(BTreeNode));
    	t->data=s[0];//根结点存在s[0]
    	tq.node=t;tq.num=1;
    	q[0]=tq;//入队
    	while(front!=rear)
    	{
    		front++;
    		tq=q[front];
    		BTree *p=tq.node;
    		int i=tq.num;//出队,取出结点及编号
    		if(2*i>length||s[2*i]=='#')//左子树为空
    		{
    			p->lchild=NULL;
    		}
    		else
    		{
    			p->lchild=(BTree*)malloc(sizeof(BTreeNode));
    			p->lchild->data=s[2*i];
    			tq.node=p->lchild;tq.num=2*i;
    			rear++;
    			q[rear]=tq;//左子女结点及其编号入队
    		}
    		if(2*i+1>length||s[2*i+1]=='#')//右子树为空
    		{
    			p->rchild=NULL;
    		}
    		else
    		{
    			p->rchild=(BTree*)malloc(sizeof(BTreeNode));
    			p->rchild->data=s[2*i+1];
    			tq.node=p->rchild;tq.num=2*i+1;
    			rear++;
    			q[rear]=tq;//右子女结点及其编号入队
    		}
    	}
    }
    
  • 相关阅读:
    幂次法则power law
    异常值探测的相关理论及方法
    Dynamics CRM2013 1:N关系 sub-grid中的“添加现有项”和“添加新建项”功能详解
    Microsoft Office Excel cannot access the file, There are several possible reasons
    matlab学习日志之并行运算
    Live555 直播源 以及MediaSubsession
    ajax跨域简单请求与复杂请求
    javaScript遍历对象、数组总结
    PHP正则表达式
    语法环境 变量 数据类型 转换 销毁和传值
  • 原文地址:https://www.cnblogs.com/tgkx1054/p/2643140.html
Copyright © 2020-2023  润新知