剑指offer(7)
剑指offer(7)
剑指 Offer 07. 重建二叉树
输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点。
假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
示例 1:
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]
示例 2:
Input: preorder = [-1], inorder = [-1]
Output: [-1]
限制:
0 <= 节点个数 <= 5000
经典重建问题,前序遍历第一个是根节点,中序遍历第一个是左子树节点,注意下标即可。
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
return build(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);
}
TreeNode* build(vector<int>& preorder,int prestart,int preend, vector<int>& inorder,int instart,int inend){
if(prestart>preend)return NULL;
TreeNode* root=new TreeNode(preorder[prestart]);
int index=-1;
for(int i=instart;i<=inend;i++){
if(preorder[prestart]==inorder[i]){
index=i;
}
}
root->left=build(preorder,prestart+1,prestart+index-instart,
inorder,instart,index-1);
root->right=build(preorder,prestart+index-instart+1,preend,
inorder,index+1,inend);
return root;
}
};
本文来自博客园,作者:{BailanZ},转载请注明原文链接:https://www.cnblogs.com/BailanZ/p/16178286.html