# 重建二叉树

#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);

}

hustspy1990

• 擅长领域：
• Java
• 性能优化
• 系统设计
• 高可用

#### 【剑指Offer】重建二叉树

2015-09-16 14:01:40

#### 剑指offer----重建二叉树---java实现

2016-07-04 17:29:39

#### 剑指Offer面试题6（Java版）：重建二叉树

2015-07-27 18:36:52

#### 剑指offer-----重建二叉树(java版)

2017-01-10 08:46:20

#### 数据结构：关于重建二叉树的三种思路

2015-11-24 00:27:46

#### 牛客网刷题--剑指offer(重建二叉树)

2016-06-29 16:42:36

#### poj2255(二叉树重建）

2014-08-06 15:24:52

#### JAVA实现重建二叉树（《剑指offer》）

2015-10-01 15:39:52

#### 剑指Offer——重建二叉树——C++

2016-11-25 10:52:45

#### 【Openjudge】重建二叉树

2017-11-03 16:50:43