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
| TreeNode* subTree(int& index, int left, int right, vector<int>& preorder, vector<int>& inorder) { if (left == right)return NULL; if (right - left == 1) { index++; return new TreeNode(inorder[left]); } TreeNode* root = new TreeNode(preorder[index]); int i = left; for (; i < right; i++) { if (inorder[i] == preorder[index]) break; } index++; root->left = subTree(index, left, i, preorder, inorder); root->right = subTree(index, i + 1, right, preorder, inorder); return root; } TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { int vsize = inorder.size(); if (vsize == 0)return NULL; else if (vsize == 1) return new TreeNode(inorder[0]); int i = 0; return subTree(i,0,vsize,preorder,inorder); }
|