二叉排序树构建和前序,中序,后续遍历实现

本文介绍了一种二叉排序树的数据结构,并详细展示了其插入操作及前序、中序、后序三种遍历方式的实现过程。通过具体的C++代码示例,深入解析了二叉树的构建与遍历算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

好久没冒过泡。。。

这次复习数据结构,搞个二叉排序树

code:

#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include <stdexcept>
#include<algorithm>
#include<stack>
#include<queue>
#include<functional>

struct BinaryNode {
	BinaryNode*lchild;
	BinaryNode*rchild;
	int data;
}BinaryTree[110];
int idx;
BinaryNode*init()
{
	BinaryTree[idx].lchild = BinaryTree[idx].rchild = NULL;
	return &BinaryTree[idx++];
}
void binaryPostOrder(BinaryNode*T)
{
	if (T->lchild != NULL)
		binaryPostOrder(T->lchild);
	if (T->rchild != NULL)
		binaryPostOrder(T->rchild);
	printf("%d ", T->data);
}
// 中序遍历
void binaryMidOrder(BinaryNode*T)
{
	if (T->lchild != NULL)
		binaryMidOrder(T->lchild);
	printf("%d ", T->data);
	if (T->rchild != NULL)
		binaryMidOrder(T->rchild);
}
// 前序遍历
void binaryPreOrder(BinaryNode*T)
{
	printf("%d ", T->data);
	if (T->lchild != NULL)
		binaryPreOrder(T->lchild);
	if (T->rchild != NULL)
		binaryPreOrder(T->rchild);
}
BinaryNode*insert(BinaryNode*T, int x)
{
	if (T == NULL)
	{
		T = init();
		T->data = x;
		return T;
	}
	else if (T->data > x)
		T->lchild = insert(T->lchild, x);
	else if (T->data < x)
		T->rchild = insert(T->rchild, x);
	return T;
}
void binaryTree()
{
	int n;
	while (scanf_s("%d", &n) != EOF)
	{
		if (n == 0)
			break;
		idx = 0;
		BinaryNode*root = NULL;
		for (int i = 0; i < n; i++)
		{
			int x;
			scanf_s("%d", &x);
			root = insert(root, x);
		}
		binaryPreOrder(root);
		printf("\n");
		binaryMidOrder(root);
		printf("\n");
		binaryPostOrder(root);
		printf("\n");
	}
}

int main(void)
{
	binaryTree();
	

	system("pause");
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值