zoukankan      html  css  js  c++  java
  • 二叉树与数组

    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;//右子女结点及其编号入队
    		}
    	}
    }
    
  • 相关阅读:
    设计模式走一遍---观察者模式
    从0打卡leetcode之day 6--最长回文串
    回车与换行的故事
    线程安全(中)--彻底搞懂synchronized(从偏向锁到重量级锁)
    线程安全(上)--彻底搞懂volatile关键字
    从0打卡leetcode之day 5 ---两个排序数组的中位数
    聊一聊让我蒙蔽一晚上的各种常量池
    从零打卡leetcode之day 4--无重复最长字符串
    C4.5算法总结
    数据库游标使用
  • 原文地址:https://www.cnblogs.com/tgkx1054/p/2643140.html
Copyright © 2011-2022 走看看