根据二叉树的先序、中序遍历结果重建二叉树

先序遍历为:1 2 4 5 3 6,中序遍历为:4 2 5 1 6 3

思路:

先序遍历的第一个元素为根节点,在中序遍历中找到这个根节点,从而可以将中序遍历分为左右两个部分,左边部分为左子树的中序遍历,右边部分为右子树的中序遍历,进而也可以将先序遍历除第一个元素以外的剩余部分分为两个部分,第一个部分为左子树的先序遍历,第二个部分为右子树的先序遍历。

由上述分析结果,可以递归调用构建函数,根据左子树、右子树的先序、中序遍历重建左、右子树。

代码:

 
 
  1. #include <stdlib.h>   
  2. #include <stdio.h>   
  3.    
  4. typedef struct TNode   
  5. {   
  6.     int value;   
  7.     TNode* lchild;   
  8.     TNode* rchild;   
  9. }TNode,*BTree;    
  10.    
  11. //根据先序遍历、中序遍历构建二叉树   
  12. BTree rebuild(int preOrder[],int startPre,int endPre,int inOrder[],int startIn,int endIn)   
  13. {   
  14.     //先序遍历和中序遍历长度应相等   
  15.     if (endPre - startPre != endIn - startIn) return NULL;   
  16.     //起始位置不应大于末尾位置   
  17.     if (startPre > endPre) return NULL;   
  18.     //先序遍历的第一个元素为根节点   
  19.     BTree tree = (BTree)malloc(sizeof(TNode));   
  20.     tree->value = preOrder[startPre];   
  21.     tree->lchild = NULL;   
  22.     tree->rchild = NULL;   
  23.     //先序遍历和中序遍历只有一个元素时,返回该节点   
  24.     if (startPre == endPre) return tree;   
  25.     //在中序遍历中找到根节点   
  26.     int index,length;   
  27.     for (index=startIn;index<=endIn;index++)   
  28.     {   
  29.         if (inOrder[index] == preOrder[startPre]) break;   
  30.     }   
  31.     //若未找到,返回空   
  32.     if (index > endIn) return NULL;   
  33.     //有左子树,递归调用构建左子树   
  34.     if (index > startIn)    
  35.     {   
  36.         length = index-startIn;   
  37.         tree->lchild = rebuild(preOrder,startPre+1,startPre+1+length-1,inOrder,startIn,startIn+length-1);   
  38.     }   
  39.     //有右子树,递归调用构建右子树   
  40.     if (index < endIn)    
  41.     {   
  42.         length = endIn - index;   
  43.         tree->rchild = rebuild(preOrder,endPre-length+1,endPre,inOrder,endIn-length+1,endIn);   
  44.     }   
  45.     return tree;   
  46. }   
  47.    
  48. //后序遍历二叉树   
  49. void postTraverse(BTree tree)   
  50. {   
  51.     if (tree->lchild != NULL) postTraverse(tree->lchild);   
  52.     if (tree->rchild != NULL) postTraverse(tree->rchild);   
  53.     printf("%d ",tree->value);   
  54. }   
  55.    
  56. int main()   
  57. {   
  58.     int preOrder[] = {1,2,4,5,3,6};   
  59.     int inOrder[] = {4,2,5,1,6,3};   
  60.     BTree tree = rebuild(preOrder,0,5,inOrder,0,5);   
  61.     postTraverse(tree);   
  62.     printf("\n");   
  63.     return 0;   
  64. }   

重建二叉树后后序遍历的结果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值