文章

105

粉丝

69

获赞

117

访问

54.2k

头像
二叉树(北京邮电大学)(传统建树) 题解:

#include<bits/stdc++.h>
using namespace std;

typedef struct Tree{
    char val;
    Tree *left, *right;
}Tree;

Tree *build(string str1, string str2)
{
    if(str1.empty() || str2.empty()) return NULL;
    
    char c = str1[0];
    Tree *root = new Tree();
    
    int index = str2.find(c);
    
    root -> val = c;
    root -> left = build(str1.substr(1, index), str2.substr(0, index));
    root -> right = build(str1.substr(index + 1), str2.substr(index + 1));
    
    return root;
}

void traversal(Tree *root)
{
    if(!root) return ;
    
    traversal(root -> left);
    traversal(root -> right);
    printf("%c", root -> val);
}

int main()
{
    string str1, str2;
    
    cin >> str1 >> str2;
    
    Tree *root = new Tree();
    root = build(str1, str2);
        
    traversal(root);
        
    printf("\n");

    return 0;
}

 

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发