Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
class Solution {
public:
void f(vector<int> &preorder,int s1, int e1,vector<int> & inorder,int s2, int e2, TreeNode *& root){
if (s1 > e1){
return;
}
if (!root){
root = new TreeNode(preorder[s1]);
int m = s2;
for(;m <= e2;m++){
if (inorder[m] == preorder[s1]){
break;
}
}
f(preorder,s1 + 1,s1 + 1 + m - 1 - s2,inorder,s2,m-1,root->left);
f(preorder,e1 - (e2 - m - 1),e1,inorder,m+1,e2,root->right);
}
}
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (!preorder.size()){
return NULL;
}
TreeNode * root = NULL;
f(preorder,0,preorder.size() -1,inorder,0,inorder.size() -1,root);
return root;
}
};
原文链接: https://www.cnblogs.com/kwill/p/3166108.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/94279
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!