由中序序列和前序序列重建二叉树

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
        int n = pre.size();
        int m = vin.size();
        if(n!=m || n == 0)
            return NULL;
        return construct(pre, vin, 0, n-1, 0, m-1);
    }
 
    TreeNode* construct(vector<int>& pre, vector<int>& vin, int l1, int r1, int l2, int r2)
    {
        TreeNode* root = new TreeNode(pre[l1]);
        if(r1 == l1)
        {
            return root;
        }
        int val = pre[l1];
        int index;
        for(index = l2; index <= r2; index ++)
        {
            if(vin[index] == val)
                break;
        }
        int left_tree_len  = index - l2;
        int right_tree_len = r2 - index;
        if(left_tree_len > 0)
            root->left = construct(pre, vin, l1+1, l1+left_tree_len, l2, index-1);
        if(right_tree_len >0 )
            root->right = construct(pre, vin, l1+1+left_tree_len, r1, index+1, r2);
        return root;
    }
};

在这里需要注意的是:给定二叉树的前序遍历(或者后序遍历)和中序遍历可以重建二叉树,而对于后序遍历和前序遍历则不能确定二叉树。(得到二叉树就可以得到相应的后序遍历序列了,代码如下)

vector<int>PostOrder;

void visit(TreeNode *t)
{
    PostOrder.push_back(t->val);
    return ;
}

void postOrder(TreeNode* r)
{
    if(r!=NULL)
    {
        postOrder(r->left);
        postOrder(r->right);
        visit(r);
    }
}

void getpost(vector<int>pre,vector<int>vin)
{
    TreeNode* root=reConstructBinaryTree(pre,vin);
    vector<int>temp;
    if(root!=NULL)
    {
        postOrder(root);
    }
    return ;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值