有关树的基本算法和练习题。

今天我来分享一下有关树的一些简单应用。

首先我们需要三个头文件:tree.h   queue.h   stack.h

#pragma once
#include<stdio.h>
#include<assert.h>
#include<Windows.h>

typedef char DataType;
typedef struct TreeNode{
	struct TreeNode *lchild;
	struct TreeNode *rchild;
	DataType data;
} TreeNode;
TreeNode *CreateNode(DataType data)
{
	TreeNode *pRoot=(TreeNode *)malloc(sizeof(TreeNode));
	pRoot->data=data;
	pRoot->lchild=0;
	pRoot->rchild=0;
}

TreeNode *CreatTree(DataType preOrder[], int size, int *pIndex)
{
	TreeNode *pRoot = CreateNode(preOrder[*pIndex]);
	if (*pIndex >= size) {
		return NULL;
	}

	if (preOrder[*pIndex] == '#') {
		*pIndex += 1;
		return NULL;
	}
	
	*pIndex += 1;	// 用了 1 个字符
	pRoot->lchild = CreatTree(preOrder, size, pIndex);
	pRoot->rchild = CreatTree(preOrder, size, pIndex);

	return pRoot;
}


#pragma once

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>

typedef TreeNode* DataType3;

typedef struct Node{
	DataType3 data;
	struct Node *Next;
}Node;

typedef struct Queue{
	Node *pFront;
	Node *pRear;
	int size;
}Queue;
//队列初始化。
void QueueInit(Queue *q)
{
	assert(q);
	q->pFront=q->pRear=NULL;
	q->size=0;
}
//队列的入队。
void QueuePush(Queue *pq,TreeNode* data)
{
	Node *pNew=(Node *)malloc(sizeof(Node));
	pq->size++;
	assert(pq);
	pNew->data=data;
	pNew->Next=NULL;

	if(pq->pRear==NULL)
	{
		pq->pRear=pNew;
		pq->pFront=pNew;
	}
	else{
		pq->pRear->Next=pNew;
		pq->pRear=pNew;
	}
}

//出队
void QueuePop(Queue *pq)
{
	Node *p=pq->pFront;
	assert(pq);
	if(pq->pFront==NULL)
	{
		pq->pRear=NULL;
	}
	else{
	pq->size--;
	pq->pFront=p->Next;
	free(p);
	}
}

//取头结点
DataType3 QueuepFront(Queue *pq)
{
	assert(pq);
	assert(pq->size>0);
	return pq->pFront->data;
}
//求是否为空队列。1为空,0不为空。
int QueueI
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值