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

}

}

熱點內容
數據加密解密演算法 發布:2024-04-19 13:25:52 瀏覽:944
安卓平板存儲空間不知道用在哪裡 發布:2024-04-19 12:58:57 瀏覽:764
出售lol腳本防封判幾年 發布:2024-04-19 12:45:14 瀏覽:187
安卓電視會員和平板哪個好 發布:2024-04-19 12:42:48 瀏覽:834
雲伺服器2m寬是多少 發布:2024-04-19 11:56:36 瀏覽:728
android層布局 發布:2024-04-19 11:52:13 瀏覽:771
1500元組裝伺服器電腦 發布:2024-04-19 11:47:25 瀏覽:469
qq改密碼怎麼改手機 發布:2024-04-19 11:39:17 瀏覽:969
電腦上如何看wifi密碼 發布:2024-04-19 11:34:14 瀏覽:416
java性能測試腳本 發布:2024-04-19 11:25:24 瀏覽:981