根据一棵树的中序遍历与后序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:
3
/
9 20
/
15 7
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal
/**
* 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:
unordered_map<int,int> hash;
TreeNode* myBuildTree(vector<int> &postorder,vector<int> &inorder,int po_left,int po_right,int in_left,int in_right){
if(po_left>po_right) return NULL;//后序遍历左边>右边 返回NULL
int postorder_root=po_right;//根节点即为后序的最后一个节点 postorder_root为根节点的下标
int inorder_root=hash[postorder[postorder_root]];//根节点的值对应于中序遍历的当前值的下标
TreeNode* root=new TreeNode(postorder[postorder_root]);//将根节点放入二叉树中
int size=inorder_root-in_left;
root->left=myBuildTree(postorder,inorder,po_left,po_left+size-1,in_left,inorder_root-1);//递归遍历左子树
root->right=myBuildTree(postorder,inorder,po_left+size,po_right-1,inorder_root+1,in_right);//递归遍历右子树
return root;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
int n=postorder.size();
for(int i=0;i<inorder.size();i++){
hash[inorder[i]]=i;//键代表inorder里面的数字,值代表inorder里面的下标
}
return myBuildTree(postorder,inorder,0,n-1,0,n-1);
}
};