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
37



struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

/**
* Build tree base on element of postorder in [i, j), and element iof inorder [m, n)
* j-i == n-m
*/
TreeNode *buildTree(vector<int> &postorder, int i, int j, vector<int> &inorder, int m, int n) { if (j <= i) return NULL; int val = postorder[j-1]; TreeNode *node = new TreeNode(val); int index = m; while(index < n && inorder[index] != val) ++index; if (index == n) { // this should be error if happen return NULL; } node->left = buildTree(postorder, i, index-m+i, inorder, m, index); node->right = buildTree(postorder, index-m+i, j-1, inorder, index+1, n); return node; } TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { // parameters position of inorder and postorder are swapped buildTree(postorder, 0, postorder.size(), inorder, 0, inorder.size()); }
View Program Text


Test Status