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

}

}

熱點內容
web伺服器python 發布:2025-05-09 15:49:50 瀏覽:176
爬蟲需要自己搭建伺服器嗎 發布:2025-05-09 15:28:48 瀏覽:108
sqldeclarevarchar 發布:2025-05-09 15:15:27 瀏覽:361
演算法是正交 發布:2025-05-09 15:13:06 瀏覽:851
php環境搭建wamp 發布:2025-05-09 15:08:43 瀏覽:910
手機存儲顯示不出來 發布:2025-05-09 15:05:21 瀏覽:924
java字元數組初始化 發布:2025-05-09 15:03:49 瀏覽:106
編譯csharp 發布:2025-05-09 15:03:44 瀏覽:604
CPA經濟資料庫 發布:2025-05-09 15:03:43 瀏覽:348
php加框 發布:2025-05-09 15:03:03 瀏覽:323