1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
class Solution { public: TreeNode* build(vector<int>& preorder, vector<int>& inorder, int pre_l, int pre_r, int in_l, int in_r) { if(pre_l>pre_r || in_l>in_r) return nullptr; int root_val = preorder[pre_l]; TreeNode* root = new TreeNode(root_val); int in_split_pos = in_l; for(int i=in_l; i<=in_r; ++i) { if(inorder[i] == root_val) { in_split_pos = i; break; } } int diff = in_split_pos - in_l; root->left = build(preorder, inorder, pre_l+1, pre_l+diff, in_l, in_split_pos-1); root->right = build(preorder, inorder, pre_l+diff+1, pre_r, in_split_pos+1, in_r); return root; } TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { int len = preorder.size(); if(len == 0) return nullptr; return build(preorder, inorder, 0, len-1, 0, len-1); } };
|