# 重建二叉树

728人阅读 评论(0)

#include <iostream>
#include <string>

using namespace std;

#define TREELEN 6

struct Node
{
Node* pLeft;
Node* pRight;
char value;
};

Node* rebuild(char *preOrder, char *inOrder, int nTreeLen)
{
Node *pTemp = new Node;
pTemp->value = *preOrder;
pTemp->pLeft = NULL;
pTemp->pRight = NULL;

cout<<pTemp->value<<endl;

int letter[26];
for(int i=0; i<26; ++i)
{
letter[i] = 0;
}
// 验证前序遍历和中序遍历字符种类个数是否一致
for(int i=0; i<nTreeLen; ++i)
{
char temp = *(preOrder+i);
if(islower(temp))
{
letter[temp-'a']++;
}
else if(isupper(temp))
{
letter[temp-'A']++;
}

temp = *(inOrder+i);
if(islower(temp))
{
letter[temp-'a']--;
}
else if(isupper(temp))
{
letter[temp-'A']--;
}
}
for(int i=0; i<26; ++i)
{
if(letter[i] != 0)
{
cout<<"error string!"<<endl;
throw runtime_error("error string!");
}
}

if(nTreeLen == 1)
{
return pTemp;
}

// 求左右子树长度
int leftTreeLen = 0;
int rightTreeLen = 0;
for(int i=0; i<nTreeLen; ++i)
{
if( *preOrder == *(inOrder+i) )
{
leftTreeLen = i;
rightTreeLen = nTreeLen - i - 1;
break;
}
}

if(leftTreeLen > 0)
{
pTemp->pLeft = rebuild(preOrder+1, inOrder, leftTreeLen);
}

if(rightTreeLen > 0)
{
pTemp->pRight = rebuild(preOrder+leftTreeLen+1, inOrder+leftTreeLen+1, rightTreeLen);
}

return pTemp;

}

void traversal(Node* root, int flag)
{
if(root == NULL)
return;
if(flag == 0)
{
cout<<root->value<<"\t";
traversal(root->pLeft, flag);
traversal(root->pRight, flag);
}
else if(flag == 1)
{
traversal(root->pLeft, flag);
cout<<root->value<<"\t";
traversal(root->pRight, flag);
}
}

int main()
{
char preOrder[TREELEN] = {'a','b','d','c','e','f'};
char inorder[TREELEN] = {'d','b','a','e','c','f'};

Node* root = NULL;
root = rebuild(preOrder, inorder, TREELEN);

cout<<"\n前序遍历："<<endl;
traversal(root, 0);
cout<<"\n中序遍历："<<endl;
traversal(root, 1);

}

个人资料
等级：
访问量： 60万+
积分： 7810
排名： 3279
博客专栏
 Java 进阶 文章：13篇 阅读：7547
最新评论