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 34 35 36
| int posorder[N], inorder[N]; struct node { int val; node *left, *right; };
node *build(int h1, int t1, int h2, int t2) { if (h1 > t1) return nullptr; node *root = new node; root->val = posorder[t1]; int index; for (; inorder[index] != posorder[t1]; index++); root->left = build(h1, index - 1 - h2 + h1, h2, index - 1); root->right = build(index - h2 + h1, t1 - 1, index + 1, t2); return root; } node *root = new node; root = build(0, n - 1, 0, n - 1);
node *build(int h1, int t1, int h2, int t2) { if (h1 > t1) return nullptr; node *root = new node; root->val = preorder[h1]; int index; for (; inorder[index] != preorder[h1]; index++); root->left = build(h1 + 1, index - h2 + h1, h2, index - 1); root->right = build(index - h2 + h1 + 1, t1, index + 1, t2); return root; }
|