链接:https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
题目:给定二叉树中序和后序遍历,构造出原二叉树。
思路:
根节点在后序遍历的最后一个位置,在中序遍历的中间位置。通过后序遍历找到根节点,然后通过中序遍历找出左右子树,然后递归构造。例如给定样例:
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
inorder, postorder
[9,3,15,20,7] , [9,15,7,20,3] ,根节点:3
inorder , postorder (左子树) inorder ,postorder(右子树)
[9] ,[9] ,根节点:9 [15,20,7] , [15,7,20],根节点:20
inorder , postorder (左子树) inorder ,postorder(右子树)
[15] ,[15] ,根节点:15 [7] ,[7] ,根节点:7
最终结果:
3
/ \
9 20
/ \
15 7
代码:
class Solution {
public:
TreeNode* build(vector<int>& inorder, vector<int>& postorder,int il , int ir ,int pl, int pr){
if(il > ir) return NULL;
int i = il;
while(inorder[i]!=postorder[pr]) i++;
TreeNode* cur = new TreeNode(postorder[pr]);
cur->left = build(inorder, postorder,il , i-1 ,pl, pl + i - il - 1);
cur->right = build(inorder, postorder,i+1 , ir ,pl + i - il , pr-1);
return cur;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return build(inorder,postorder,0,inorder.size()-1,0,postorder.size()-1);
}
};