首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 其他相关 >

二叉树相干

2013-10-29 
二叉树相关#include iostreamusing namespace std#define TREELEN 6struct NODE{NODE* pLeftNODE* pRi

二叉树相关
#include <iostream>using namespace std;#define TREELEN 6struct NODE{NODE* pLeft;NODE* pRight;char chValue;};void ReBuild(char* pPreOrder, char* pInOrder, int nTreeLen, NODE** pRoot){if(nTreeLen<1){return;}*pRoot=new NODE;(*pRoot)->pLeft=NULL;(*pRoot)->pRight=NULL;(*pRoot)->chValue=*pPreOrder;int lNum=0;//左子树节点个数 int rNum=0;//有子树节点个数 for(int i=0;i<nTreeLen;i++){if(*pPreOrder==*(pInOrder+i)){lNum=i;break;}}rNum=nTreeLen-1-lNum;if(lNum>=1){ReBuild(pPreOrder+1, pInOrder, lNum, &((*pRoot)->pLeft));}if(rNum>=1){ReBuild(pPreOrder+1+lNum, pInOrder+1+lNum, rNum, &((*pRoot)->pRight));}}void printTree(NODE* pRoot){if(pRoot==NULL)return;cout<<pRoot->chValue<<", ";if(pRoot->pLeft!=NULL){cout<<"l="<<pRoot->pLeft->chValue<<", ";}else{cout<<"l=NULL, ";}if(pRoot->pRight!=NULL){cout<<"r="<<pRoot->pRight->chValue<<endl;}else{cout<<"r=NULL"<<endl;}printTree(pRoot->pLeft);printTree(pRoot->pRight);}int main(){char szPreOrder[TREELEN]={'a','b','d','c','e','f'};char szInOrder[TREELEN]={'d','b','a','e','c','f'};NODE* pRoot=NULL;ReBuild(szPreOrder, szInOrder, TREELEN, &pRoot);printTree(pRoot);}

?

?

?

热点排行