当前位置:首页 » 编程语言 » c语言构造树

c语言构造树

发布时间: 2023-03-26 11:20:54

A. 请问c语言如何创建二叉树

创建二叉树的源程序如下:

#include <cstdlib>

#include <stdio.h>

typedef struct node

{ //树的结点

int data;

struct node* left;

struct node* right;

} Node;

typedef struct

{ //树根

Node* root;

} Tree;

void insert(Tree* tree, int value)//创建树

{

Node* node=(Node*)malloc(sizeof(Node));//创建一个节点

node->data = value;

node->left = NULL;

node->right = NULL;

if (tree->root == NULL)//判断树是不是空树

{

tree->root = node;

}

else

{//不是空树

Node* temp = tree->root;//从树根开始

while (temp != NULL)

{

if (value < temp->data)//小于就进左儿子

{

if (temp->left == NULL)

{

temp->left = node;

return;

}

else

{//继续判断

temp = temp->left;

}

}

else {//否则进右儿子

if (temp->right == NULL)

{

temp->right = node;

return;

}

else {//继续判断

temp = temp->right;

}

}

}

}

return;

}

void inorder(Node* node)//树的中序遍历

{

if (node != NULL)

{

inorder(node->left);

printf("%d ",node->data);

inorder(node->right);

}

}

int main()

{

Tree tree;

tree.root = NULL;//创建一个空树

int n;

scanf("%d",&n);

for (int i = 0; i < n; i++)//输入n个数并创建这个树

{

int temp;

scanf("%d",&temp);

insert(&tree, temp);

}

inorder(tree.root);//中序遍历

getchar();

getchar();

return 0;

}


(1)c语言构造树扩展阅读:

简单二叉树定义范例:此树的顺序结构为:ABCDE

#include <cstdlib>

#include <stdio.h>

#include <string>

int main()

{

node* p = newnode;

node* p = head;

head = p;

string str;

cin >> str;

creat(p, str, 0)//默认根结点在str下标0的位置

return 0;

}

//p为树的根结点(已开辟动态内存),str为二叉树的顺序存储数组ABCD##E或其他顺序存储数组,r当前结点所在顺序存储数组位置

void creat(node* p, string str, int r)

{

p->data = str[r];

if (str[r * 2 + 1] == '#' || r * 2 + 1 > str.size() - 1)p->lch = NULL;

else

{

p->lch = newnode;

creat(p->lch, str, r * 2 + 1);

}

if (str[r * 2 + 2] == '#' || r * 2 + 2 > str.size() - 1)p->rch = NULL;

else

{

p->rch = newnode;

creat(p->rch, str, r * 2 + 2);

}

}

热点内容
ipad文件加密 发布:2024-05-02 08:20:30 浏览:442
粉土压缩模量 发布:2024-05-02 07:53:59 浏览:805
国都证券初始密码是多少 发布:2024-05-02 07:46:39 浏览:109
shell脚本和linux命令行 发布:2024-05-02 07:37:54 浏览:968
自己的服务器搭建微信小程序商城 发布:2024-05-02 07:36:26 浏览:426
php单行注释 发布:2024-05-02 07:36:22 浏览:958
买车哪些配置必备 发布:2024-05-02 07:30:20 浏览:52
华为手机的自带铃声文件夹 发布:2024-05-02 07:20:14 浏览:501
xp系统开机密码怎么设置 发布:2024-05-02 06:49:48 浏览:759
柱加密区公式 发布:2024-05-02 06:40:19 浏览:4