根据前序和中序序列还原二叉树
class Solution {
public:
TreeNode* _buildTree(vector<int>& preorder,vector<int>& inorder,int& prevIndex,int inBegin,int inEnd)
{
if(prevIndex >= preorder.size())
return nullptr;
//中序序列不存在
if(inEnd < inBegin)
return nullptr;
//将中序序列分割成左子树和右子树
int inRoot = inBegin;
for(int i = inBegin;i <= inEnd;i++)
{
if(inorder[i] == preorder[prevIndex])
{
//根节点在中序序列中的位置
inRoot = i;
break;
}
}
//创建根节点
TreeNode* root = new TreeNode(preorder[prevIndex]);
prevIndex++;
//左子树
root->left = _buildTree(preorder,inorder,prevIndex,inBegin,inRoot-1);
//右子树
root->right = _buildTree(preorder,inorder,prevIndex,inRoot+1,inEnd);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int prevIndex = 0;
return _buildTree(preorder,inorder,prevIndex,0,inorder.size()-1);
}
};
根据中序和后序序列还原二叉树
class Solution {
public:
TreeNode* _buildTree(vector<int>& inorder,vector<int>& postorder,int& postIndex,int inBegin,int inEnd)
{
if(postIndex < 0)
return nullptr;
if(inBegin > inEnd)
return nullptr;
//后序序列从后向前遍历依次为根->右孩子->左孩子
//根据后序序列中的根节点在中序序列中找到位置下标
int inIndex = inBegin;
for(int i = inBegin;i <= inEnd;i++)
{
if(postorder[postIndex] == inorder[i])
{
inIndex = i;
break;
}
}
//创建根节点
TreeNode* root = new TreeNode(postorder[postIndex]);
postIndex--;
//创建左子树
root->right = _buildTree(inorder,postorder,postIndex,inIndex+1,inEnd);
root->left = _buildTree(inorder,postorder,postIndex,inBegin,inIndex-1);
return root;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
int postIndex = postorder.size()-1;
return _buildTree(inorder,postorder,postIndex,0,inorder.size()-1);
}
};