重建二叉树(面试题 6)

题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。

思想:使用分治法建左右子树。

#include <stdio.h>  
#include <stdlib.h>  
  
typedef struct tree  
{  
        int id;  
        struct tree * lc;  
        struct tree * rc;  
}tree, *p_tree;  
  
p_tree  root;  
int *pre, *mid;  
  
  
int creat_tree( int low, int high, p_tree *t, int m_low, int m_high )  
{  
     int i, count = 0, f1, f2;  
     int flag;  
       
     if( high - low != m_high - m_low )  
     {  
         return 0;  
     }  
     if( low > high )    // 细节  
     {  
         return 1;  
     }  
  
     (*t) = ( p_tree )malloc( sizeof( tree ) );  
     (*t)->id = pre[low];  
     (*t)->lc = NULL;  
     (*t)->rc = NULL;  
       
   //  if( low == high ) // 细节  
    // {  
     //    return 1;  
    // }  
       
     flag = 0;  
  
     for( i = m_low; i <= m_high; i++ )  
     {  
          if( mid[i] == pre[low] )  
          {  
              flag = 1;  
              break;  
          }  
          else  
          {  
              count++;  
          }  
     }  
       
     if( flag )  
     {  
        f1 = creat_tree( low + 1, low + count, &((*t)->lc), m_low, m_low + count - 1 );  
  
        if( !f1 )  
        {  
            return 0;  
        }  
  
        f2 = creat_tree( low + count + 1, high, &((*t)->rc), m_low + count + 1, m_high );  
  
        return f2;  
     }  
     else  
     {  
         return 0;  
     }  
}  
  
void out_put( p_tree t )  
{  
     if( t )  
     {  
         out_put( t->lc );  
         out_put( t->rc );  
           
         printf("%d ", t->id);  
     }  
}  
  
int main()  
{  
    int i, n;  
      
    while( scanf("%d", &n) != EOF )  
    {  
           pre = ( int* )malloc( sizeof( int ) * n );  
           mid = ( int* )malloc( sizeof( int ) * n );  
           for( i = 0; i < n; i++ )  
           {  
                scanf("%d", &pre[i]);  
           }  
             
           for( i = 0; i < n; i++ )  
           {  
                scanf("%d", &mid[i]);  
           }  
             
           if( creat_tree( 0, n - 1, &root, 0, n - 1 ) )  
           {  
                out_put( root );  
           }  
           else  
           {  
               printf("No");  
           }  
           printf("\n");  
    }   
      
    return 0;  
}  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值