首页 > 其他 > 详细

华中尔科技大机试 二叉树遍历 Easy *两序列构建二叉树

时间:2020-03-05 01:07:22      阅读:74      评论:0      收藏:0      [点我收藏+]

基本思想:

要求用两个序列构建新的二叉树,标准写法,注意下;

 

关键点:

无;

 

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<map>
#include<set>
using namespace std;

string s1, s2;

struct node {
    char data;
    node* left;
    node* right;
};

node* charge(int l1, int r1, int l2, int r2) {
    if (l1 > r1)
        return NULL;
    int index = -1;
    for (int i = l2; i <= r2; i++) {
        if (s2[i] == s1[l1])
            index = i;
    }
    node* no = new node;
    no->data = s1[l1];
    no->left = charge(l1+1,l1+index-l2,l2,index-1);
    no->right = charge(l1+index-l2+1,r1,index+1,r2);
    return no;
}

void postorder(node* root) {
    if (root == NULL)
        return;
    postorder(root->left);
    postorder(root->right);
    cout << root->data;
}

int main() {
    while (cin >> s1>> s2) {
        node* root = charge(0, s1.size() - 1, 0, s2.size() - 1);
        postorder(root);
        cout << endl;
    }
    return 0;
}

 

华中尔科技大机试 二叉树遍历 Easy *两序列构建二叉树

原文:https://www.cnblogs.com/songlinxuan/p/12416985.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!