由前序遍历和中序遍历重建二叉树

来源:互联网 发布:固定收益部 收入 知乎 编辑:程序博客网 时间:2024/06/05 08:33
#include<iostream>
#include<string>
#include<vector>
using namespace std;
struct Binarynode{
int m_value;
Binarynode* m_left;
Binarynode* m_right;
Binarynode(int value) :m_value(value), m_left(NULL), m_right(NULL){};
};
class solution {
public:
Binarynode* construct_core(int* preorderstart, int*preorderend, int* inorderstart, int* inorderend)
{
Binarynode* tree = new Binarynode(*preorderstart);
tree->m_left = NULL;
tree->m_right = NULL;
if (preorderstart == preorderend)
{
if (inorderstart == inorderend)
{
if (*preorderstart == *inorderstart)
return tree;
else
throw std::exception("invalid input");
}
}
int* root = preorderstart;
int* temp = inorderstart;
while (*temp != *root)
temp++;
int left_length=temp - inorderstart;
if (left_length>0)
tree->m_left=construct_core(preorderstart+1,preorderstart+left_length,inorderstart,inorderstart+left_length-1);
if (left_length < preorderend - preorderstart)
tree->m_right = construct_core(preorderstart + left_length + 1, preorderend, temp + 1, inorderend);
return tree;
}
Binarynode* get_tree(int* preorderstart, int* inorderstart, int length)
{
Binarynode* tree;
if (preorderstart == NULL || inorderstart == NULL || length == 0)
return NULL;
else
{
tree = construct_core(preorderstart, preorderstart + length - 1, inorderstart, inorderstart + length - 1);
}
return tree;
}
void printtree(Binarynode* tree)
{
if (tree != NULL)
{
printtree(tree->m_left);//目前是中序遍历,调换该行和下一行的顺序就是前序遍历
cout << tree->m_value;
printtree(tree->m_right);
}
}
};
int main()
{
int a[8] = {1,2,4,7,3,5,6,8 };
int b[8] = { 4,7,2,1,5,3,8,6};
solution s;
Binarynode* tree;
tree=s.get_tree(a, b, 8);
s.printtree(tree);
cout << endl;
return 0;
}
原创粉丝点击