数据结构第九周 :(数组存储的完全二叉树的先序遍历 + 二叉树的创建及求解二叉树的宽度 + 层次遍历二叉树 + 二叉树的深度及结点最远距离 + 中序线索二叉树)

数组存储的完全二叉树的先序遍历

【问题描述】课后作业习题25:n个结点的完全二叉树顺序存储在一维数组a中,设计一个算法,实现对此二叉树的先序遍历。

【输入形式】一维数组a,以#结束输入,请接收后存储在一维数组a中

【输出形式】先序遍历序列

【样例输入】ABCDEF#

【样例输出】ABDECF

#include<iostream>
#include<queue>
#include<cstring>
#include<stdlib.h>
#define N 20
using namespace std;

typedef struct node
{
    char data;
    struct node * LChild;
    struct node * RChild;
}BtNode,*BiTree;

void CreatBt(BiTree * root)
{
    queue<BiTree> q;
    char a[N];
    cin >> a;
    int pos = 0;
    int len = strlen(a) - 1;
    *root = (BiTree)malloc(sizeof(BtNode));
    (*root)->data = a[pos ++];
    (*root)->LChild = NULL; //要考虑一个结点的情况,考虑完备性
    (*root)->RChild = NULL;
    BtNode * temp = (*root);
    q.push(temp);
    while(!q.empty())
    {
        temp = q.front();
        q.pop();
        if(pos < len)
        {
            temp->LChild = (BiTree)malloc(sizeof(BtNode));
            temp->LChild->data = a[pos];
            pos ++;
            temp->LChild->LChild = NULL;
            temp->LChild->RChild = NULL;
            q.push(temp->LChild);
            //cout<<pos<<temp->LChild->data;
        }
        else break;
        if(pos <len)
        {
            temp->RChild = (BiTree)malloc(sizeof(BtNode));
            temp->RChild->data = a[pos];
            pos ++;
            temp->RChild->LChild = NULL;
            temp->RChild->RChild = NULL;
            q.push(temp->RChild);
            //cout<<pos<<temp->LChild->data;
        }
        else break;
    }
}

void PreOrder(BiTree root)
{
    if(root == NULL)
        return ;
    else
    {
        cout<<root->data;
        PreOrder(root->LChild);
        PreOrder(root->RChild);
    }
    return ;
}

int main()
{
    BtNode * root;
    CreatBt(&root);
    PreOrder(root);
    return 0;
}

二叉树的创建及求解二叉树的宽度

【问题描述】求解二叉树的宽度,请用递归和非递归两种方法求解。

【输入形式】前序和中序序列建树

【输出形式】递归和非递归求解的宽度值

【样例输入】

abcdefg

cbdaegf

【样例输出】

3 3

#include<iostream>
#include<cstring>
#include<stdlib.h>
#include<queue>
#define N 40
using namespace std;
typedef struct node
{
    char data;
    struct node * LChild;
    struct node * RChild;
}BtNode, *BiTree;

int w[N];
int Max = -1;

void Creat(BiTree * root, string Pre, string In, int PreLeft, int PreRight, int InLeft, int InRight)
{
    if(InLeft > InRight)
        *root = NULL; //创建节点过程中唯一一个置空的地方
    else
    {
        *root = (BiTree)malloc(sizeof(BtNode));
        (*root)->data = Pre[PreLeft];
        int mid = 0;
        while(In[mid] != Pre[PreLeft])
        {
            mid ++;
        }
        Creat(&((*root)->LChild), Pre, In, PreLeft + 1, PreLeft + mid - InLeft, InLeft, mid - 1);
        Creat(&((*root)->RChild), Pre, In, PreLeft + mid - InLeft + 1, PreRight, mid + 1, InRight);
    }
}

void OrderWidth(BtNode * root,int k) //用递归的方法求树的宽度,维护最大宽度
{
    if(root == NULL)
        return ;
    else
    {
        w[k] ++;
        if(Max < w[k]) Max = w[k];
        OrderWidth(root->LChild, k + 1);
        OrderWidth(root->RChild, k + 1);
    }
}

int FindMaxWidth(BtNode * root)
{
    queue<BiTree> q;
    q.push(root);
    int maxw = 0;
    while(!q.empty())
    {
        int w = 0;
        BtNode * over = q.back();
        while(!q.empty())
        {
            BtNode * temp = q.front();
            q.pop();
            if(temp->LChild != NULL)
            {
                q.push(temp->LChild);
                w ++;
            }
            if(temp->RChild != NULL)
            {
                q.push(temp->RChild);
                w ++;
            }
            if(temp == over) break;
        }
        if(w > maxw) maxw = w;
    }
    return maxw;
}

int main()
{
    string Pre;
    string In;
    cin>>Pre>>In;
    int len = Pre.length();
    BtNode * root;
    Creat(&root, Pre, In, 0, len - 1, 0, len - 1);
    int i = 0;
    for(i = 0; i < N; i ++)
    {
        w[i] = 0;
    }
    OrderWidth(root,0);
    cout<<Max<<" ";
    int MaxWidth = FindMaxWidth(root);
    cout<<MaxWidth;
    return 0;
}

层次遍历二叉树

【问题描述】 考研真题:给定一颗二叉树,要求从下至上按层遍历二叉树,每层的访问顺序是从左到右,每一层单独输出一行。

【输入形式】 广义表表示的二叉树,结点元素类型为整型,且都大于0,例如:1( 2( 3 ( 4, 5 ) ), 6( 7, 8( 9, 10 ) ) )

【输出形式】 从下至上,打印每一层的结点元素值,元素间以空格隔开。每层的访问顺序是从左到右,每一层单独输出一行。

【样例输入】 1(2(3(4,5)),6(7,8(9,10))),字符串内没有空格

【样例输出】

4 5 9 10

3 7 8

2 6

1

【评分标准】 本题目主要考察两个知识点: 1.创建二叉树存储结构 2.按层次遍历二叉树的算法

#include<stdio.h>
#include<stdlib.h>						// malloc()
#include<string.h>						// strlen(), memset()

#define MAXSIZE 100

typedef struct node
{
	int data;
	int depth;						//记录深度,同一深度输出到同一行
	struct node *lchild, *rchild;
}BtNode, * BiTree;

int a[MAXSIZE][2];						//二维数组,分别记录节点值和深度

BiTree create_BT()
{
	BiTree stack[MAXSIZE], p = NULL, T = NULL;
	char ch, s[MAXSIZE] = {0}, num[10] = {0};
	int flag = 0, top = -1, len, i = 0, j = 0, sum = 0;

	fgets(s, MAXSIZE-1, stdin);			//先读到数组中,这样做,数据就可以重复读了!
	len = strlen(s);

	while(1)
	{
		memset(num, '\0', 10);			//每次别忘了对num清零!
		ch = s[i];

		if(s[i] >= '0' && s[i] <= '9')	        //发现一个字符是'0'~'9',可能是多位数
        {
            j = 0;
            while(s[i] >= '0' && s[i] <= '9')
            {
                num[j++] = s[i++];
            }
            sscanf(num, "%d", &sum);	                //sscanf字符串转数字
        }
        else
            i++;					//如果不是数字,要i++,下次就可以读下一个字符

        if( ch == '\n' || i >= len)		        //发现'\n'或者是s[]到头了就返回
            return T;
		else
		{
			switch(ch)
			{
				case '(' : stack[++top] = p;
						   flag = 1;
						   break;
				case ')' : top--;
						   break;
				case ',' : flag = 2;
						   break;
				default  : p = (BiTree)malloc(sizeof(BtNode));
						   p -> data = sum;
						   p -> depth = 0xfffffff;
						   p -> lchild = NULL;
						   p -> rchild = NULL;
						   if(T == NULL)
						   {
								T = p;
								p -> depth = 1;			//记录深度
						   }
						   else if(flag == 1)
								{
									stack[top] -> lchild = p;
									p -> depth = top+2;	//记录深度
								}
						   else
								{
									stack[top] -> rchild = p;
									p -> depth = top+2;	//记录深度
								}
			}
		}
	}
}

int layer(BiTree T)
{
	BiTree queue[MAXSIZE], p;
	int front, rear, i = 0;
	if(T != NULL)
	{
		queue[0] = T;
		front = -1;
		rear = 0;
		while(front < rear)
		{
			p = queue[++front];
			a[i][0] = p -> data;
			a[i++][1] = p -> depth; //将遍历的节点记录到a[][]
			if(p->rchild != NULL) //先右,便是从右至左遍历
				queue[++rear] = p -> rchild;
			if(p->lchild != NULL)
				queue[++rear] = p -> lchild;
		}
	}

	return --i;	 //返回节点个数!别忘了是--i
}

int main()
{
	BiTree T;
	int i = 0, dep;

	T = create_BT(); //根据广义表构建树
	i = layer(T); //按层遍历,从右至左

	dep = a[i][1];
	for(; i>=0; i--) //遍历所有的节点以输出
	{
		if(dep!=a[i][1]) //如果发现深度跟之前的不同,就换行
		{
			printf("\n");
			dep = a[i][1];
		}
		printf("%d ", a[i][0]);
	}
	return 0;
}

二叉树的深度及结点最远距离

【问题描述】考研真题:求二叉树的深度及二叉树中最远两个结点的距离。

【输入形式】拓展的前序遍历序列

【输出形式】深度和距离

【样例输入】AB#C##DE#G#H##F##

【样例输出】5 6

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;

typedef struct node
{
    char data;
    struct node * LChild;
    struct node * RChild;
}BtNode, * BiTree;

int MaxDistance = 0;
void Creat(BiTree * root)
{
    char c;
    c = getchar();
    if(c == '#')
    {
        *root = NULL;
    }
    else
    {
        *root = (BiTree)malloc(sizeof(BtNode));
        (*root)->data = c;
        Creat(&((*root)->LChild));
        Creat(&((*root)->RChild));
    }
}

int FindHeight(BtNode * root)
{
    if(root == NULL) return 0;
    int LeftHeight = FindHeight(root->LChild);
    int RightHeight = FindHeight(root->RChild);
    if(MaxDistance < LeftHeight + RightHeight)
        MaxDistance = LeftHeight + RightHeight;
    return max(LeftHeight, RightHeight) + 1;
}

int main()
{
    BtNode * root = NULL;
    Creat(&root);
    int MaxHeight = FindHeight(root);
    cout<<MaxHeight<<" "<<MaxDistance;
    return 0;
}

中序线索二叉树

【问题描述】创建一棵二叉树,接着中序线索化该二叉树,然后编写相应函数遍历该中序线索二叉树

【编码要求】线索二叉树遍历过程中不能使用递归、不能使用栈。

【输入形式】二叉树拓展的前序遍历序列

【输出形式】中序遍历序列

【样例输入】AB#D##CE###

【样例输出】BDAEC

#include<iostream>
#include<stdlib.h>
#include<stdio.h> //getchar的头文件
using namespace std;

typedef struct node
{
    char data;
    struct node * LChild;
    struct node * RChild;
    bool LTag; //默认为0
    bool RTag;
}BtNode, *BiTree;

BtNode * pre = NULL;

void Creat(BiTree *root) //根据拓展前序创建一棵二叉树
{
    char c;
    c = getchar();
    if(c == '#')
        *root = NULL;
    else
    {
        *root = (BiTree)malloc(sizeof(BtNode));
        (*root)->data = c;
        Creat(&((*root)->LChild));
        Creat(&((*root)->RChild));
    }
}

void InThread(BtNode * root)
{
    if(root != NULL)
    {
        InThread(root->LChild);

        if(root->LChild == NULL) //加线索的操作
        {
            root->LTag = 1;
            root->LChild = pre;
        }
        if(pre != NULL && pre->RChild == NULL) //大判断root已经不为空,所以判断pre是否为空,排除第一个结点的情况
        {
            pre->RTag = 1;
            pre->RChild = root;
        }
        pre = root;

        InThread(root->RChild);
    }
}

BtNode * InNext(BtNode * p) //返回中序线索二叉树遍历中的后继节点
{
    if(p == NULL) return NULL;
    BtNode * next = NULL;
    if(p->RTag == 1)
    {
        next =  p->RChild;
    }
    else
    {
        BtNode *q = NULL;
        for(q = p->RChild; q->LTag == 0; q = q->LChild); //知道找到最左端叶子节点时跳出循环
        next =  q;
    }
    return next;
}

BtNode * InFirst(BtNode * p) //在中序线索二叉树上找遍历的第一个节点
{
    BtNode * q = p;
    if(q == NULL) return q;
    while(q->LTag == 0) q = q->LChild;
    return q;
}

void TInOrder(BtNode * root) //遍历中序线索二叉树
{
    BtNode * p;
    p = InFirst(root);
    while(p != NULL)
    {
        cout<<p->data;
        p = InNext(p);
    }
}

int main()
{
    BtNode * root = NULL;
    Creat(&root);
    InThread(root);

    pre -> RTag = 1; //要把线索二叉树的最后一个节点的右孩子加上为空的线索
    pre -> RChild = NULL;

    TInOrder(root);
    return 0;
}
  • 4
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一只可爱的小猴子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值