LC 二叉树通过两种遍历创建二叉树问题

**题目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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值