zoukankan      html  css  js  c++  java
  • 1364:二叉树遍历(flist)

    【题目描述】

    树和二叉树基本上都有先序、中序、后序、按层遍历等遍历顺序,给定中序和其它一种遍历的序列就可以确定一棵二叉树的结构。

    假定一棵二叉树一个结点用一个字符描述,现在给出中序和按层遍历的字符串,求该树的先序遍历字符串。

    【输入】

    两行,每行是由字母组成的字符串(一行的每个字符都是唯一的),分别表示二叉树的中序遍历和按层遍历的序列。

    【输出】

    一行,表示二叉树的先序序列。

    【输入样例】

    DBEAC
    ABCDE

    【输出样例】

    ABDEC

    #include <bits/stdc++.h>
    using namespace std;
    
    struct Node {
        char value;
        Node *left, *right;
    };
    
    string GetLevel(const string &level, const string &pre)
    {
        string new_level;
        for (int i = 0; i < level.size(); i++) {
            if (pre.find(level[i]) != string::npos) {
                new_level.push_back(level[i]);
            }
        }
        return new_level;
    }
    
    Node *CreateTree(const string &pre, const string &level)
    {
        if (pre.size() <= 0) {
            return NULL;
        } else {
            // cout << pre << "," << level << endl;
            Node *root = new Node;
            root->value = level[0];
            int pos = pre.find(level[0]);
            string pre1 = pre.substr(0, pos);
            string level1 = GetLevel(level, pre1);
            root->left = CreateTree(pre1, level1);
            string pre2 = pre.substr(pos + 1);
            string level2 = GetLevel(level, pre2);
            root->right = CreateTree(pre2, level2);
            return root;
        }
    }
    
    string PreOrder(Node *root)
    {
        string s;
        if (root != NULL) {
            s.push_back(root->value);
            s += PreOrder(root->left);
            s += PreOrder(root->right);
        }
        return s;
    }
    
    string InOrder(Node *root)
    {
        string s;
        if (root != NULL) {
            s += InOrder(root->left);
            s.push_back(root->value);
            s += InOrder(root->right);
        }
        return s;
    }
    
    string PostOrder(Node *root)
    {
        string s;
        if (root != NULL) {
            s += PostOrder(root->left);
            s += PostOrder(root->right);
            s.push_back(root->value);
        }
        return s;
    }
    
    int main()
    {
        // freopen("1.txt", "r", stdin);
        string pre = "DBEAC", level = "ABCDE";
        cin >> pre >> level;
        Node *root = CreateTree(pre, level);
        cout << PreOrder(root) << endl;
        // cout << InOrder(root) << endl;
        // cout << PostOrder(root) << endl;
        return 0;
    }
  • 相关阅读:
    动态传参
    函数的介绍
    文件的操作
    send email with formatted table
    minimize and close window with customed winform
    python algorithm
    something important about docker
    book list
    which language is suitable for what to do
    Find Duplicate Items in list fast
  • 原文地址:https://www.cnblogs.com/gaojs/p/14942349.html
Copyright © 2011-2022 走看看