栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

leecode 第144题: 二叉树的前序遍历 C语言完整版

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

leecode 第144题: 二叉树的前序遍历 C语言完整版

#include 

typedef struct Node{
	int val;
	struct Node* Lchild;
	struct Node* Rchild;
}*BTree, BTnode;


int CreaTree(BTree* T) {
	int data;
	scanf_s("%d", &data);

	if (data == 0x0)
		*T = NULL;
	else {
		*T = (BTree)malloc(sizeof(BTnode));
		if (*T == 0)
		{
			printf("malloc space error!");
			return 0;
		}
		else {
			(*T)->val = data;
		}
		CreaTree(&(*T)->Lchild);
		CreaTree(&(*T)->Rchild);
	}
	return 1;
}


void preorder(BTree T, int* res, int* resSize) {
	if (T == NULL)
		return;
	else {
		res[*resSize] = T->val;
		printf("%dt", T->val);
		*resSize += 1;
		preorder(T->Lchild,res,resSize);
		preorder(T->Rchild, res, resSize);

	}
}

int* preorderTraversal(BTree T, int* returnSize) {
	int* res = malloc(sizeof(int)* 501);
	returnSize = malloc(sizeof(int));

	*returnSize = 0;
	preorder(T,res,returnSize);

	return res;
}


void DestoryBTree(BTree* T) {
	if (*T) {
		if ((*T)->Lchild){
			DestoryBTree(&(*T)->Lchild);
		}
		if ((*T)->Rchild) {
			DestoryBTree(&(*T)->Rchild);
		}
		free(*T);
		*T = NULL;
	}
}

int main(void)
{
	BTree T;
	int* res1 = (int *)malloc(sizeof(int));

	while (1) {
		printf("请输入二叉树,以0作为结束:n");
		CreaTree(&T);

		printf("前序遍历的结果为:n");
		preorderTraversal(T, res1);

		DestoryBTree(&T);
		printf("n销毁二叉树完成,请输入新二叉树。n");
	}
	return 0;
}

循环输入:

a. 1 0 2 3 0 0 0

b. 0

c. 1 0 0

d.1 2 0

e.1 0 2 0 0

涉及知识点:

1.二叉树的创建:CreaTree

2.二叉树的前序遍历:preorder

3.二叉树的销毁:DestoryBTree

4.指针内存的申请和释放;

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/587587.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号