题解 | #二叉树遍历#

二叉树遍历

https://www.nowcoder.com/practice/6e732a9632bc4d12b442469aed7fe9ce

#include <iostream>
#include <string>
using namespace std;

struct Node {
    char data;
    Node* leftT;
    Node* rightT;
    Node(char c): data(c), leftT(NULL), rightT(NULL){}
};

Node * build(string prestr, string midstr){
    if(prestr.length() == 0)
        return NULL;
    Node* node = new Node(prestr[0]);
    int pos = midstr.find(prestr[0]);//在中序字符串中找到根结点的坐标
    node->leftT = build(prestr.substr(1, pos), midstr.substr(0, pos));
    node->rightT = build(prestr.substr(pos + 1), midstr.substr(pos + 1));
    return node;
}
//后序遍历
void inOrder(Node* node){
    if(node == NULL)
        return;
    inOrder(node->leftT);
    inOrder(node->rightT);
    cout << node->data;
}

int main() {
    string str1, str2;
    while (cin >> str1 >> str2) {
        Node* root = build(str1, str2);
        inOrder(root);
        cout << endl;
    }

    return 0;
}

全部评论

相关推荐

用微笑面对困难:这里面最强的是驾驶证了,可以入职美团大厂,然后直接开启黄马褂人生
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务