题目一:输入某二叉树前序和中序遍历的结果,重建二叉树。
思路:在前序遍历中第一个就是根结点,然后到中序遍历中找到这个根节点就能分出左右子树,然后递归就可以了
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution1 {
public:
vector<int> preorder, inorder;
//声明一个哈希表,因为我们需要迅速找到根节点在中序遍历序列的位置,时间是O(1)。
map<int,int> hash;
TreeNode* buildTree(vector<int>& _preorder, vector<int>& _inorder)
{
if(_preorder.size()==0||_inorder.size()==0) return nullptr;
preorder=_preorder;inorder=_inorder;
for(int i=0;i<inorder.size();i++) hash[inorder[i]]=i;
return dfs(0,preorder.size()-1,0,inorder.size()-1);
}
//pl 当前前序遍历数组的开头
//pr 当前前序遍历数组的结尾
//pr 当前中序遍历数组的开头
//pr 当前中序遍历数组的结尾
TreeNode* dfs(int pl,int pr,int il,int ir)
{
if(pl>pr||il>ir) return nullptr;
//根据前序遍历序列的第一个数字创建根结点
TreeNode* root=new TreeNode(preorder[pl]);
int k=hash[root->val];//根节点在中序遍历序列的位置
if(root->val!=inorder[k]) return NULL;//检查前序序列和中序序列是否匹配
root->left=dfs(pl+1,pl+k-il,il,k-1); //pl+1+k-il-1
root->right=dfs(pl+k-il+1,pr,k+1,ir);
return root;
}
};
题目二:输入某二叉树中序和后序遍历的结果,重建二叉树,同理,在后序遍历中最后一个节点就是根结点
class Solution {
public:
map<int,int> hash;
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
if(postorder.size()==0||inorder.size()==0||postorder.size()!=inorder.size())
return nullptr;
for(int i=0;i<inorder.size();i++)hash[inorder[i]]=i;
return Create(inorder,postorder,0,postorder.size()-1,0,inorder.size()-1);
}
TreeNode* Create(vector<int>& inorder, vector<int>& postorder,int pl,int pr,int il,int ir)
{
if(pl>pr||il>ir) return nullptr;
//这里是后序序列的最后一个节点
TreeNode* root=new TreeNode(postorder[pr]);
int k=hash[root->val];
if(root->val!=inorder[k]) return nullptr;
//这2行递归是核心代码
root->left=Create(inorder,postorder,pl,pr-ir+k-1,il,k-1);
root->right=Create(inorder,postorder,pr-ir+k,pr-1,k+1,ir);
return root;
}
};