题目链接:
https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
难度:中等
106. 从中序与后序遍历序列构造二叉树
根据一棵树的中序遍历与后序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
有点难。。。。
递归还是比较舒服的 迭代没看懂 emmm… 有时间在看吧 (明日复明日。。。。 我果然是个辣鸡 记个坐标题解)
中序 左根右
后序 左右根
对于后序的最后遍历的位置应该是根节点,可以再中序中找出根节点的位置,根节点的左侧为左子树,右侧为右子树
要注意 后序过程中,我们要从后方开始循环,那也就意味着 我们会先碰到右子树(如果 存在)
/**
* 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> unmap;
// 位置 后序序列的末尾
int pos;
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
// postorder的末尾
pos=postorder.size()-1;
// i 对应的下标
// 初始化unmap
int i=0;
for(auto a:inorder){
unmap[a]=i++;
}
return dfs(0,inorder.size()-1,inorder,postorder);
}
// left right
TreeNode* dfs(int left,int right,vector<int>& inorder,vector<int>& postorder){
// 跳出条件
// 这里的左右是inorder的边界
if(left>right){
return nullptr;
}
// 后序的最后一个位置
// 根节点
int curroot=postorder[pos];
// 建立节点
TreeNode* root=new TreeNode(curroot);
// 找出在中序inorder中的下标
int curpos=unmap[curroot];
// 后序位置减一
// 此时指向右子树的根节点 (若存在)
pos--;
// left curpos(根节点) right
root->right=dfs(curpos+1,right,inorder,postorder);
root->left=dfs(left,curpos-1,inorder,postorder);
return root;
}
};