106. 从中序与后序遍历序列构造二叉树
思路:
根据后序遍历的最后一个元素是根的性质逐步构造出二叉树。
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> a, b;
TreeNode * dfs(int al, int ae, int bl, int be){
if(al > ae) return NULL;
TreeNode * res = new TreeNode(b[be]);
int idx;
for(int i = al; i <= ae; i ++) if(a[i] == b[be]) { idx = i; break; }
res->left = dfs(al, idx - 1, bl, bl + idx - al - 1);
res->right = dfs(idx + 1, ae,bl + idx - al, be - 1);
return res;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
a = inorder;
b = postorder;
TreeNode * res = dfs(0, a.size() - 1, 0, b.size() - 1);
return res;
}
};