//Construct Binary Tree from Inorder and Postorder
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode{
int val;
TreeNode *left, *right;
TreeNode(int data): val(data), left(NULL), right(NULL){
}
};
class Solution{
public:
//根据中序和后序遍历 构建二叉树
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder){
return buildTree(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1);
}
TreeNode *buildTree(vector<int> &inorder, int iLeft, int iRight, vector<int> &postorder, int pLeft, int pRight) {
if(iLeft > iRight || pLeft > pRight){
return NULL;
}
TreeNode *cur = new TreeNode (postorder[pRight]);
int i = 0;
for(i = iLeft; i < inorder.size(); ++i){
if(inorder[i] == cur->val){
break;
}
}
cur->left = buildTree(inorder, iLeft, i - 1, postorder, pLeft, pLeft + i - iLeft - 1);
cur->right = buildTree(inorder, i + 1, iRight, postorder, pLeft + i - iLeft, pRight - 1);
return cur;
}
//根据前序和中序遍历 构建二叉树
TreeNode *buildTree2(vector<int> &preorder, vector<int> &inorder){
return buildTree2(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1);
}
TreeNode *buildTree2(vector<int> &preorder, int iLeft, int iRight, vector<int> &inorder, int pLeft, int pRight) {
if(iLeft > iRight || pLeft > pRight){
return NULL;
}
TreeNode *cur = new TreeNode(preorder[iLeft]);
int i;
//for(i = 0; i < inorder.size(); ++i){
for(i = pLeft; i <= pRight; ++i){
if(inorder[i] == cur->val){
break;
}
}
cur->left = buildTree2(preorder, iLeft + 1, iLeft + i - pLeft , inorder, pLeft , i - 1);
cur->right = buildTree2(preorder, iLeft + i - pLeft + 1, iRight, inorder, i + 1, pRight);
return cur;
}
};
//前序遍历输出
void PreorderDisplay(TreeNode *root){
if(root == NULL){
return ;
}
else
{
cout << root->val <<" ";
PreorderDisplay(root->left);
PreorderDisplay(root->right);
}
}
//后序遍历输出
void PostorderDisplay(TreeNode *root){
if(root == NULL){
return ;
}
else
{
PostorderDisplay(root->left);
PostorderDisplay(root->right);
cout << root->val << " ";
}
}
int main(){
Solution s;
TreeNode *res, *res1;
vector<int> inorder = {11,4,5,13,8,9};
vector<int> preorder = {5,4,11,8,13,9};
vector<int> postorder = {11,4,13,9,8,5};
// res = s.buildTree(inorder, postorder);
// PreorderDisplay(res);
// cout << endl;
cout << 2 << endl;
res1 = s.buildTree2(preorder, inorder);
cout << 2 << endl;
//cout << res1->val << endl;
PostorderDisplay(res1);
system("pause");
return 0;
}
根据前序 中序 后序 构建二叉树
最新推荐文章于 2023-01-16 21:36:56 发布