要求:根据中序和后序遍历序列构建一棵二叉树
代码如下:
1 struct TreeNode {
2 int val;
3 TreeNode *left;
4 TreeNode *right;
5 TreeNode(int x): val(x),left(NULL), right(NULL) {}
6 };
7
8 typedef vector<int>::iterator Iter;
9
10 TreeNode *buildTreeFromInorderPostorder(vector<int> &inorder, vector<int> &postorder)
11 {
12 return buildBinaryTreeResur(inorder.begin(), inorder.end(), postorder.begin(), postorder.end());
13 }
14
15 TreeNode *buildBinaryTreeResur(Iter istart, Iter iend, Iter pstart, Iter pend)
16 {
17 if (istart == iend || pstart == pend)
18 return NULL;
19 int ival = *(pend-1);
20 Iter ptemp = find(istart, iend, ival);
21 TreeNode *res = new TreeNode(ival);
22 res->left = buildBinaryTreeResur(istart, ptemp, pstart, pstart+(ptemp-istart));
23 res->right = buildBinaryTreeResur(ptemp+1, iend, pstart+(ptemp-istart), pend-1);
24 return res;
25 }