思想:递归实现
#include<iostream>
#include<string>
#include<stack>
using namespace std;
struct Node
{
int value;
Node *left;
Node *right;
};
Node *ContructBinaryTree(int *pre,int *in,int length,Node *root)
{
if(length == 0)
return NULL;
root = new Node();
root->value = pre[0];
root->left = NULL;//将左子树和右子树的节点地址初始化,防止出现野指针
root->right = NULL;
if(length == 1)
return root;
else
{
int mid;
for(int i = 0;i < length;++i)
if(in[i] == root->value)
{
mid = i;
break;
}
root->left = ContructBinaryTree(pre + 1,in,mid,root);//构造以root为根的左子树
root->right = ContructBinaryTree(pre + mid + 1,in + mid + 1,length - mid - 1,root);//构造以root为根的右子树
return root;
}
}
void preOrder(Node *head)
{
if(head != NULL)
{
cout<<head->value<<endl;
preOrder(head->left);
preOrder(head->right);
}
}
int main()
{
int pre[7] = {3,2,6,5,1,4,7};
int in[7] = {5,6,2,3,4,1,7};
Node *head = ContructBinaryTree(pre,in,7,head);
preOrder(head);
return 0;
}