【面试题】根据前序遍历和中序或中序和后序遍历树构造二叉树

根据前序遍历和中序遍历树构造二叉树
思路:(https://blog.csdn.net/mmwwxx123/article/details/81510702)该链接中已经提到。直接上代码:

class Solution {
public:
    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
     int len = vin.size();
        if(len == 0){
            return NULL;
        }
        vector<int> left_pre, right_pre;
        vector<int> left_in, right_in;
        TreeNode *root = new TreeNode(pre[0]);
        int index =-1;
        for(int i=0; i<len; i++){
            if(vin[i] == pre[0]){
                index = i;
                break;
            }
        }

        for(int i=0; i<index; i++){
            left_pre.push_back(pre[i+1]);
            left_in.push_back(vin[i]);
        }
        for(int i=index+1; i<len; i++){
            right_pre.push_back(pre[i]);
            right_in.push_back(vin[i]);
        }

        root->left = reConstructBinaryTree(left_pre, left_in);
        root->right = reConstructBinaryTree(right_pre, right_in);       

        return root;
    }
};

根据中序遍历和后序遍历树构造二叉树
解题思路
思路和用前序遍历和后序遍历树构造二叉树类似
1、首先根据后序遍历序列的最后一个数字创建根结点(后序遍历序列的最后一个数字就是根结点)
2、然后在中序遍历序列中找到根结点所在的位置,这样就能确定左、右子树结点的数量,这样也就分别找到了左、右子树的中序遍历序列和后序遍历序列。
3、然后用递归的方法去构建左、右子树,直到叶子结点。
根据中序加后序遍历重建二叉树

代码如下:

class Solution {
public:
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
        if(inorder.size()==0||postorder.size()==0)
            return NULL;
        if(inorder.size()!=postorder.size())
            return NULL;
        int root_index=-1;
        vector<int> inL,inR,postL,postR;
        int len=postorder.size();
        TreeNode *root=new TreeNode(postorder[len-1]);
        for(int i=0;i<len;i++)
        {
            if(postorder[len-1]==inorder[i])
            {
                root_index=i;
                break;
            }
        }

        for(int j=0;j<root_index;j++)
        {
            postL.push_back(postorder[j]);
            inL.push_back(inorder[j]);
        }
        int k=root_index+1;
        for(;k<inorder.size();k++)
        {
            postR.push_back(postorder[k-1]);
            inR.push_back(inorder[k]);
        }

        root->left=buildTree(inL,postL);
        root->right=buildTree(inR,postR);
        return root;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值