美文网首页
根据二叉树的先序遍历结果输出中序遍历

根据二叉树的先序遍历结果输出中序遍历

作者: 匿名client | 来源:发表于2019-07-07 23:14 被阅读0次

    题目描述

    编一个程序,读入用户输入的一串先序遍历字符串,根据此字符串建立一个二叉树(以指针方式存储)。 例如如下的先序遍历字符串: ABC##DE#G##F### 其中“#”表示的是空格,空格字符代表空树。建立起此二叉树以后,再对二叉树进行中序遍历,输出遍历结果。

    输入描述:

    输入包括1行字符串,长度不超过100。

    输出描述:

    可能有多组测试数据,对于每组数据,
    输出将输入字符串建立二叉树后中序遍历的序列,每个字符后面都有一个空格。
    每个输出结果占一行。

    示例1

    输入

    abc##de#g#f###

    输出

    c b e g d f a

    #include <iostream>
    #include <string>
    using namespace std;
     
    string str;
    int i;
     
    struct TreeNode  //树节点
    {
        char value; //节点的值
        struct TreeNode *lchild, *rchild;
        TreeNode(char c): value(c), lchild(NULL), rchild(NULL){} //初始化
    };
    TreeNode* creatTree() //创建树
    {
        char c = str[i++];
        if (c == '#') return NULL;
        TreeNode *root = new TreeNode(c);
        root->lchild = creatTree();
        root->rchild = creatTree();
        return root;
    }
    void inorder(TreeNode* root) //中序遍历
    {
        if (!root) return;
        inorder(root->lchild);
        cout << root->value <<" ";
        inorder(root->rchild);
    }
    void deleteTree(TreeNode* root) //删除构建的树防止内存泄露
    {
        if (root->lchild != NULL) 
        {
            deleteTree(root->lchild);
            root->lchild = NULL;
        }
        if (root->rchild != NULL) 
        {
            deleteTree(root->rchild);
            root->rchild = NULL;
        }
        delete(root);
    }
    int main()
    {
        while(cin >> str)
        {
            i = 0;
            TreeNode *root = creatTree();
            inorder(root);
            cout << endl;
            deleteTree(root);
        }
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:根据二叉树的先序遍历结果输出中序遍历

          本文链接:https://www.haomeiwen.com/subject/nslwhctx.html