1.从前序与中序遍历序列构造二叉树
根据一棵树的前序遍历与中序遍历构造二叉树。注意:你可以假设树中没有重复的元素。
考察知识点:递归
思路:(1)前序中左起第一位肯定是根结点,我们可以据此找到中序中根结点的位置inroot;
(2)中序中根结点左边就是左子树结点,右边就是右子树结点,即[左子树结点,根结点,右子树结点],我们就可以得出左子树结点个数为int leftnum = inroot - inleft;;
(3)前序中结点分布应该是:[根结点,左子树结点,右子树结点],根据前一步确定的左子树个数,可以确定前序中左子树结点和右子树结点的范围;
(4)如果我们要前序遍历生成二叉树的话,下一层递归应该是:
左子树:root->left = pre_order(前序左子树范围,中序左子树范围,前序序列,中序序列);;
右子树:root->right = pre_order(前序右子树范围,中序右子树范围,前序序列,中序序列);。
(5)每一层递归都要返回当前根结点root。
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
return Tree(0,preorder.size()-1,0,inorder.size()-1,preorder,inorder);
}
TreeNode* Tree(int preleft,int preright,int inleft,int inright,vector<int>& preorder, vector<int>& inorder){
if(preleft>preright||inleft>inright) return nullptr; //*
TreeNode* root=new TreeNode(preorder[preleft]);
int inroot=inleft;
while(inorder[inroot]!=preorder[preleft]) ++inroot;
int leftnum=inroot-inleft;
root->left=Tree(preleft+1,preleft+leftnum,inleft,inleft+leftnum-1,preorder,inorder);
root->right=Tree(preleft+leftnum+1,preright,inleft+leftnum+1,inright,preorder,inorder);
return root;
}
};
2.从中序与后序遍历序列构造二叉树
根据一棵树的中序遍历与后序遍历构造二叉树。注意:你可以假设树中没有重复的元素。
考察知识点:递归
思路:(1)后序中右起第一位肯定是根结点,我们可以据此找到中序中根结点的位置inroot;
(2)中序中根结点左边就是左子树结点,右边就是右子树结点,即[左子树结点,根结点,右子树结点],我们就可以得出左子树结点个数为int rightnum = inright - inroot;;
(3)后序中结点分布应该是:[左子树结点,右子树结点,根结点],根据前一步确定的右子树个数,可以确定后序中左子树结点和右子树结点的范围;
(4)如果我们要前序遍历生成二叉树的话,下一层递归应该是:
左子树:root->left = pre_order(中序左子树范围,后序左子树范围,中序序列,后序序列);;
右子树:root->right = pre_order(中序右子树范围,后序右子树范围,中序序列,后序序列);。
(5)每一层递归都要返回当前根结点root。
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return Tree(0,inorder.size()-1,0,postorder.size()-1,inorder,postorder);
}
TreeNode* Tree(int inleft,int inright,int postleft,int postright,vector<int>& inorder, vector<int>& postorder){
if(inleft>inright||postleft>postright) return nullptr;
TreeNode *root=new TreeNode(postorder[postright]);
int inroot=inright;
while(inorder[inroot]!=postorder[postright]) --inroot;
int rightnum=inright-inroot;
root->left=Tree(inleft,inright-rightnum-1,postleft,postright-rightnum-1,inorder,postorder);
root->right=Tree(inright-rightnum+1,inright,postright-rightnum,postright-1,inorder,postorder);
return root;
}
};