這是一段關於二叉樹的代碼。*list_from_tree這個函數是用來建立二叉樹的,但我不太懂它是如何建立二叉樹的,求大神詳細解釋。
#include
#include
typedef struct tnode Tnode;
struct tnode{
Tnode *left;
Tnode *right;
int data;
};
Tnode *new_tnode(int data);
void print_tree(Tnode *tree, int depth);
void free_tree(Tnode *tree);
typedef struct lnode Lnode;
struct lnode{
Lnode *next;
int data;
};
Lnode *new_node(int data);
void print_list(Lnode *list);
void free_list(Lnode *list);
Lnode *list_from_tree(Tnode *root, Lnode *list);
int main(int argc, char *argv[]){
Tnode *root = new_tnode(6);
root->left = new_tnode(5);
root->right = new_tnode(8);
root->right->left = new_tnode(7);
root->right->right = new_tnode(9);
Lnode *list = list_from_tree(root, NULL);
print_tree(root, 0);
printf("\n");
print_list(list);
free_list(list);
free_tree(root);
return EXIT_SUCCESS;
}
Lnode *new_node(int data){
Lnode *new = malloc(sizeof(Lnode));
new->next = NULL;
new->data = data;
return new;
}
Tnode *new_tnode(int data){
Tnode *new = malloc(sizeof(Tnode));
new->left = NULL;
new->right = NULL;
new->data = data;
return new;
}
void print_tree(Tnode *tree, int depth){
if(tree != NULL){
printf("(");
print_tree(tree->left, depth+1);
if(tree->left == NULL){
printf("x");
}
printf("<-");
printf("%d", tree->data);
printf("->");
if(tree->right == NULL){
printf("x");
}
print_tree(tree->right, depth+1);
printf(")");
}
}
void print_list(Lnode *list){
Lnode *curr = list;
while(curr != NULL){
printf("%d -> ", curr->data);
curr = curr->next;
}
printf("x\n");
}
void free_tree(Tnode *tree){
if(tree != NULL){
free_tree(tree->left);
free_tree(tree->right);
free(tree);
}
}
void free_list(Lnode *list){
Lnode *curr = list;
Lnode *tmp;
while(curr != NULL){
tmp = curr;
curr = curr->next;
free(tmp);
}
}
Lnode *list_from_tree(Tnode *root, Lnode *list){
if(root == NULL){
return list;
}
Lnode *right = list_from_tree(root->right, list);
Lnode *new = new_node(root->data);
new->next = right;
Lnode *left = list_from_tree(root->left, new);
return left;
}
你理解錯了,listfromtree是根據二叉樹得到一個鏈表,不是構建二叉樹。用的辦法就是簡單的遞歸,把找到的插入鏈表尾部。