《剑指offer》面试题6重建二叉树
来源:互联网 发布:如何成为网络写手游戏 编辑:程序博客网 时间:2024/06/09 23:49
#include <iostream>using namespace std;typedef struct Binary_Node{ int value; struct Binary_Node *left; struct Binary_Node *right;}BinaryNode;int pre_order[1010];int in_order[1010];int flag;BinaryNode *BuildTree(int *start_pre,int *end_pre, int *start_in,int *end_in){ BinaryNode *root=new BinaryNode; root->value=*start_pre; root->left=root->right=NULL; if(start_pre== end_pre) { if(start_in==end_in && *start_pre==*start_in) return root; else { flag=0; } } //在中跟序列中找到根节点的值 int *rootInOrder=start_in; while(rootInOrder<=end_in&& *rootInOrder!=root->value) rootInOrder++; int leftLength = rootInOrder-start_in; int rightLength = end_in - rootInOrder; int *leftPriEnd = start_pre+leftLength; if (leftLength >0) { root->left= BuildTree(start_pre+1,leftPriEnd,start_in,rootInOrder-1); } else { //flag=0; } if(leftLength<end_pre- start_pre) { root->right=BuildTree(leftPriEnd+1,end_pre,rootInOrder+1,end_in); } else { //flag=0; } return root;}void print(BinaryNode *root){ if(root!=NULL) { print(root->left); print(root->right); if(root!=NULL) { cout<<root->value<<' '; } }}int main(){ int length; while(cin>>length) { for(int i=0;i<length;i++) cin>>*(pre_order+i); for(int i=0;i<length;i++) cin>>*(i+in_order); flag=1; BinaryNode *node=new BinaryNode; int *start_pre=&pre_order[0]; int *end_pre =&pre_order[length-1]; int *start_in =&in_order[0]; int *end_in =&in_order[length-1]; node=BuildTree(start_pre,end_pre,start_in,end_in); if (flag) { print(node); cout<<endl; } else cout<<"No"<<endl; } return 0;}
0 0
- 《剑指Offer》面试题-重建二叉树
- 剑指offer--面试题6: 重建二叉树(树)
- 剑指offer-->面试题6 重建二叉树
- 【剑指offer】面试题6:重建二叉树
- 《剑指offer》面试题6:重建二叉树
- 剑指offer 面试题6 重建二叉树
- 剑指Offer:面试题6 重建二叉树
- 《剑指offer》面试题6:重建二叉树
- 《剑指offer》面试题6重建二叉树
- 剑指offer面试题6--重建二叉树
- 理解《剑指Offer》之面试题6 重建二叉树
- 剑指offer 面试题6 重建二叉树
- 剑指offer面试题6 重建二叉树(c)
- 剑指offer面试题6 重建二叉树(java)
- 《剑指Offer》面试题6:重建二叉树
- 剑指offer--面试题6:重建二叉树--Java实现
- 【剑指Offer学习】【面试题6 :重建二叉树】
- 《剑指Offer》学习笔记--面试题6:重建二叉树
- 关于java字节的问题,所以说明全在注释里面了,百分之百手敲,注意细节
- R语言学习由浅入深路线图
- HDU 1392 Surround the Trees 凸包的周长
- eclipse中maven配置
- R语言入门基础教程:常用运算函数
- 《剑指offer》面试题6重建二叉树
- quartz框架调度
- 从头调试6q linux bsp
- HashMap与HashTable
- Android应用开发-小巫CSDN博客客户端之显示博文详细内容
- 用自己的话理解理解zookeeper(自认为纠正了网上的一些说法)
- R语言与机器学习学习笔记(分类算法)
- socket在windows和linux下的区别
- HDU 2215 Maple trees 凸包+最小圆覆盖