实验3 | 由遍历序列构造二叉树

二叉树构造定理:

  • 定理7.1:任何n(n>0)个不同结点的二又树,都可由它的中序序列和先序序列唯一地确定。  
  • 定理7.2:任何n(n>0)个不同结点的二又树,都可由它的中序序列和后序序列唯一地确定。

1.1 已知先序序列为ABDGCEF,中序序列为DGBAECF,则构造二叉树的过程如下所示。 

1.1.1 C代码:

#include<stdio.h>
#include<malloc.h>

typedef struct node
{
    struct node *lchild, *rchild;
    char data;
} BTNode;

BTNode* CreateBTree(char *pre, char *in, int n)
{
    int k;
    char *p;
    if (n <= 0)
        return NULL;
    BTNode *b = (BTNode*)malloc(sizeof(BTNode));
    b->data = *pre;
    for (p = in; p < in + n; ++p)
        if (*p == *pre)
            break;
    k = p-in;
    b->lchild = CreateBTree(pre+1, in, k);
    b->rchild = CreateBTree(pre+k+1, p+1, n-k-1);
    return b;
}

void dispBTree(BTNode *b) 
{
    if(b!= NULL)
    {
        printf("%c", b->data);
        if(b->lchild != NULL || b->rchild != NULL)
        {
            printf("(");
            dispBTree(b->lchild); 
            if(b->rchild != NULL)
              printf(",");
            dispBTree(b->rchild);
            printf(")");                 
        }
    }
 } 

int main()
{
    BTNode* b;
    char pre[] = "ABDGCEF";
    char in[] = "DGBAECF";
    int n = 7;
    b = CreateBTree(pre, in, 7);
    dispBTree(b);
    return 0; 
}

1.1.2 C++代码:

/**
 * 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* buildTree(vector<int>& preorder, vector<int>& inorder) 
    {
      TreeNode *b = CreateBTree(preorder.begin(), inorder.begin(), inorder.size());
        return b;    
    }
    
    TreeNode* CreateBTree(vector<int>::iterator p, vector<int>::iterator q, int n)
    {
        TreeNode *b;
        auto s = q;
        int k;
        if(n <= 0)
            return nullptr;
        b = new TreeNode(*p);
        for(; s < q + n; ++s)
            if(*s == *p)
                break;
        k = s - q;
        b->left = CreateBTree(p+1, q, k);
        b->right = CreateBTree(p+k+1, s+1, n-k-1);
        return b;
    }
};

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值