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

}

}

熱點內容
熱血傳奇腳本怎麼做 發布:2025-09-18 20:29:06 瀏覽:603
軒逸手動經典有哪些配置 發布:2025-09-18 20:20:40 瀏覽:619
安卓手機下載軟體在哪裡設置密碼 發布:2025-09-18 20:10:08 瀏覽:602
net業務緩存框架 發布:2025-09-18 19:57:14 瀏覽:9
pythonrst 發布:2025-09-18 19:28:50 瀏覽:407
頁面訪問在線升級 發布:2025-09-18 19:13:46 瀏覽:776
相機存儲滿 發布:2025-09-18 19:12:19 瀏覽:757
如何搭載我的世界伺服器 發布:2025-09-18 19:02:39 瀏覽:431
c語言組框 發布:2025-09-18 19:02:23 瀏覽:947
如何看見真我手機的全部配置 發布:2025-09-18 18:48:10 瀏覽:980