**题目1 :从中序与后序遍历序列构造二叉树 **
根据一棵树的中序遍历与后序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
思路:
这类问题的解法是统一的,使用递归来完成比较方便,唯一不同的是在建树过程中, 传入的参数可能因为入参的改变而改变;
// 1. 递归函数返回条件:左右索引交叉
// 2, 对当前传入的 后序遍历中的最后一个结点,也就是根节点进行创建
// 3. 判断是否 左索引= 右索引,如果相等就可以直接返回这个节点,因为没有对应的左子树和右子树了
// 4. 找到中序遍历的根节点位置,并依据这个位置创建左右子树(也就是递归调用函数创建左子树和右子树)
代码:
/**
* 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:
TreeNode* build(vector<int>& inorder, vector<int>& postorder, int in_start, int in_end, int post_start, int post_end)
{
if(in_start > in_end || post_start> post_end){return NULL;}
TreeNode* root = new TreeNode(postorder[post_end]);
// 如果边界重合,直接返回这个节点,不需要建立相应的左子树和右子树了
if(in_start == in_end) return root;
// 建立相应的左子树和右子树:首先求出in 和 post的边界,可以找到in的边界位置,post通过in来计算元素个数即可得到
int in_root_index = in_start;
while(inorder[in_root_index] != postorder[post_end])
in_root_index++;
// in : 左根右;;;post: 左右根
root->left = build(inorder, postorder,in_start, in_root_index -1,
post_start, post_start+(in_root_index-1 - in_start));
root->right = build(inorder, postorder,in_root_index+1,in_end,
post_end-1 -(in_end - in_root_index - 1) ,post_end-1);
return root;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
TreeNode* root = build(inorder, postorder, 0, inorder.size()-1, 0, postorder.size()-1);
return root;
}
};