Frankjunyu 2015-11-05 13:41 采纳率: 58.8%
浏览 1483
已采纳

关于c语言二叉树的问题,求大神解答,急

这是一段关于二叉树的代码。*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;

}

  • 写回答

2条回答 默认 最新

  • threenewbee 2015-11-05 14:03
    关注

    你理解错了,listfromtree是根据二叉树得到一个链表,不是构建二叉树。用的办法就是简单的递归,把找到的插入链表尾部。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao