當前位置:首頁 » 編程語言 » 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);

}

}

熱點內容
php5php7 發布:2023-06-08 10:28:39 瀏覽:604
linux查看埠號佔用 發布:2023-06-08 10:26:45 瀏覽:540
光碟壓縮文件解壓後怎麼看 發布:2023-06-08 10:25:48 瀏覽:716
mysql存儲過程排序 發布:2023-06-08 10:23:50 瀏覽:337
linux載入變數 發布:2023-06-08 10:23:09 瀏覽:572
手機屏密碼忘了怎麼解鎖 發布:2023-06-08 10:23:08 瀏覽:432
如何將蘋果手機的通訊錄轉到安卓手機 發布:2023-06-08 10:22:10 瀏覽:868
打開共享文件夾慢 發布:2023-06-08 10:21:15 瀏覽:289
戰意什麼伺服器最好 發布:2023-06-08 10:18:45 瀏覽:556
資料庫設計論壇 發布:2023-06-08 10:17:57 瀏覽:145