根据先序中序求后序的递归算法

本文提供了一个使用递归方法在C++中构建二叉树的代码示例,通过预序遍历和中序遍历来创建树结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

很久以前写过,现在把我的递归版本代码贴出

  1. struct tree  
  2. {  
  3.     char c;  
  4.     struct tree * left_child;  
  5.     struct tree * right_child;  
  6. } * root;  
  7. tree * create_tree(char pre[], char in[], int len)  
  8. {  
  9.     if (len == 0) return NULL;  
  10.     tree * t = new tree;  
  11.     t->c = pre[0];  
  12.     int i;  
  13.     for (i = 0; i < len; ++i)  
  14.         if (in[i] == pre[0])  
  15.             break;  
  16.     int j;  
  17.     t->left_child = create_tree(pre + 1, in, i);  
  18.     t->right_child = create_tree(pre + i + 1, in + i + 1, len - i - 1);  
  19.     return t;  
  20. }  
  21. void print(tree * t) {  
  22.     if (t == NULL) return ;  
  23.     print(t->left_child);      
  24.     print(t->right_child);  
  25.     cout<<t->c;  
  26. }  
  27. int main()  
  28. {  
  29.     char pre[30], in[30];  
  30.     root = new tree;  
  31.     while (scanf("%s%s", pre, in) == 2) {  
  32.         root = create_tree(pre, in, strlen(pre));  
  33.         print(root);  
  34.         printf("\n");  
  35.     }  
  36.     return 0;  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值