二叉树相关

本节主要是为了写二叉树类型题目练手的代码,重点培养运用“指针”。

《编程之美》3.9重建二叉树 : 已知前序和中序,重建二叉树

#include <iostream>
using namespace std;

#define TREELEN 6
struct 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);
}

猜你喜欢

转载自chuanwang66.iteye.com/blog/1950552
今日推荐