博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
temp
阅读量:7303 次
发布时间:2019-06-30

本文共 1915 字,大约阅读时间需要 6 分钟。

1 #include 
2 3 using namespace std; 4 5 struct Node 6 { 7 Node(int v):value(v),left(NULL), right(NULL){} 8 struct Node * left; 9 struct Node * right;10 int value;11 };12 int length;13 Node * BuildTree(int * preorder, int * inorder, int * pos, int start, int end)14 {15 if((*pos) >= length) return NULL;16 //if(start >= end) return NULL;17 Node * root = new Node(preorder[*pos]);18 int i;19 for(i = start; i < end; ++i)20 if(inorder[i] == preorder[*pos])21 break;22 //if(i == end) return NULL;23 24 if(i > start)25 {26 *pos = *pos + 1;27 root->left = BuildTree(preorder, inorder, pos, start, i);28 }29 if(end > i+1)30 {31 *pos = *pos + 1;32 root->right = BuildTree(preorder, inorder, pos, i+1, end);33 }34 return root;35 36 }37 void InorderOutput(Node * root)38 {39 if(NULL == root) return;40 InorderOutput(root->left);41 cout << root->value << " ";42 InorderOutput(root->right);43 }44 void FreeTree(Node * root)45 {46 if(NULL == root) return;47 FreeTree(root->left);48 FreeTree(root->right);49 delete root;50 }51 int main()52 {53 int n;54 while(cin >> n)55 {56 length = n;57 int * preorder = new int[n];58 int * inorder = new int[n];59 for(int i = 0; i < n; ++i)60 cin >> preorder[i];61 for(int j = 0; j < n; ++j)62 cin >> inorder[j];63 int k = 0;64 Node * root = BuildTree(preorder, inorder, &k, 0, n);65 InorderOutput(root);66 cout << endl;67 // if(isTree)68 // cout << "Yes" << endl;69 // else cout << "NO" << endl;70 delete preorder;71 delete inorder;72 FreeTree(root);73 }74 return 0;75 }

转载于:https://www.cnblogs.com/xubin0523/archive/2012/10/08/2715702.html

你可能感兴趣的文章
Windows Server 2008搭建***服务
查看>>
实验一 路由配置(cisco packet tracer)
查看>>
装机流程
查看>>
练习题7
查看>>
简单的nginx启动脚本
查看>>
我的友情链接
查看>>
React Native集成到Android项目当中
查看>>
cd ls
查看>>
linux学习命令总结⑩①
查看>>
【好程序员笔记分享】C语言之交换变量的值
查看>>
linux 安装和初级优化
查看>>
C#系列-多样化的程序分支[7]
查看>>
Keepalived配置文件详解(以Haproxy作为负载均衡器)
查看>>
megacli创建RAID10过程详解
查看>>
Linux系统引导过程
查看>>
【apache】mod_proxy 和 mod_rewrite实现js跨域
查看>>
林锐博士谈考研
查看>>
Vant Weapp小程序蹲坑之使用checkbox组件
查看>>
重载operator<<运算符时第二个参数最好不要写成指向对象的指针
查看>>
在ubuntu上编译 wpa_supplicant-2.6
查看>>