剑指offer--面试题7:重建二叉树

来源:互联网 发布:淘宝一天最多几个好评 编辑:程序博客网 时间:2024/06/05 04:32

#include <stdio.h>   #include <iostream>  using namespace std;  typedef struct Node  {    struct Node* left;    struct Node* right;    char  data;  }*BTree;  BTree Construct_Tree(char* pre, char* in, int length)          {    if( pre==NULL || in==NULL || length <= 0 )        return NULL;       char root_value = pre[0];                        //第一个结点为根节点   Node* root=new Node(); //申请根节点空间  root->data=root_value; //数据域  root->left = root->right =NULL; //指针域  for(int i = 0;i < length; ++i) //找到根节点在inorder中的位置  {    if(in[i] == root_value)                           break;      }    //如果root存在左孩子   if(i!=0) root->left=Construct_Tree( pre+1,in, i );//左孩子  //如果root存在右孩子    if(i!=length-1) root->right=Construct_Tree( pre+i+1,in+i+1, length-(i+1) );//右孩子   cout<<root->data;    //测试用,面试算法中可去掉  return root;  }int main()  {      char* pr="12473568";      char* in="47215386";   //测试printf("已知前序遍历序列:%s\n",pr);printf("已知中序遍历序列:%s\n",in);    printf("二叉树建成! \n后序遍历序列为:");BTree T=Construct_Tree(pr,in, 8);    printf("\n");      return 0;  }  


原创粉丝点击