#include<iostream>
#include<vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class MyClass
{
public:
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
return buildTree(inorder, postorder, 0, inorder.size() - 1, 0, postorder.size() - 1);
}
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder, int inLeft, int inRight, int
poLeft, int poRight){
if (inLeft > inRight || poLeft > poRight)
{
return NULL;
}
TreeNode* root = new TreeNode(postorder[poRight]);
int i = 0;
for ( i = inLeft; i < inorder.size(); i++)
{
if (inorder[i] == root->val)
{
break;
}
}
root->left = buildTree(inorder, postorder, inLeft, i - 1, poLeft, poLeft + i - inLeft - 1);
root->right = buildTree(inorder, postorder, i + 1, inRight, poLeft + i - inLeft, poRight-1);
return root;
}
};
一些学习心得和体会。不敢妄称原创,基本是学习笔记。致谢相关大神的引用
根据后序中序构造二叉树
最新推荐文章于 2024-06-11 20:37:41 发布