根据后序与中序遍历建树层序遍历输出

在我心里只要是二叉树就一定与递归有千丝万缕的关系,因此先递归建立左子树,再递归右子树,

像递归这种东西,一定要站在一个高度去看他,如果想的太复杂了会越陷越深,所以写代码是只要

给他一个宏观上的指令,就可以了。层序遍历吧,代码很简单,看一遍应该就理解了。

#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
#include <cstdlib>

using namespace std;

int mid[100],post[100],pre[100];
int n;
struct node
{
    int c;
    node *lchild,*rchild;
};

//根据后序遍历与中序遍历递归建树
node *postMidCreatTree(int len, int *mid, int *post)
{
    int i;
    if(len<=0)
        return NULL;
    node *p = (node *)malloc(sizeof(node));
    p->lchild = p-> rchild = NULL;
    p->c = post[len-1];
    for(i=0; i<n; ++i)
        if(mid[i] == post[len-1])
            break;
    int l=i;
    p->lchild = postMidCreatTree(l,mid,post);
    p->rchild = postMidCreatTree(len-l-1,mid+l+1,post+l);
    return p;
}

//层序遍历
int levelTraverseTree(node *head)
{
    queue<node *>q;
    q.push(head);
    int i=0;

    while(!q.empty())
    {
        node *t;
        t = q.front();
        q.pop();
        pre[i++] = t->c;
        if(t->lchild)
        q.push(t->lchild);
        if(t->rchild)
        q.push(t->rchild);
    }

    return i;
}

int main()
{
    cin >> n;

    for(int i=0; i<n; ++i)
        cin >> post[i];
    for(int i=0; i<n; ++i)
        cin >> mid[i];

    node *head = (node *)malloc(sizeof(node));
    head->lchild = head->rchild = NULL;
    head = postMidCreatTree(n,mid,post);

    int len = levelTraverseTree(head);

    for(int i=0; i<len-1; ++i)
        cout << pre[i] << " ";
    cout << pre[len-1] << endl;
    return 0;
}


你遇到的问题是:**输入字符串中包含了空格(`A B # D # # C # #`)**,而你的代码在读取时使用了 `cin >> input`,它会只读取第一个单词(即 `"A"`),后面的字符没有被完整读入,导致建树失败,最终只生成了一个根节点 `A`。 --- ### ❌ 错误原因总结: - 输入为:`A B # D # # C # #`(用空格分隔) - 但程序期望的是无空格的连续字符串:`AB#D##C##` - 使用 `cin >> input` 只读到第一个非空字符序列 `"A"`,其余被忽略 --- ### ✅ 解决方案 你需要 **读取一整行输入,去除所有空格**,才能正确解析扩展前序序列。 --- ### ✅ 修改后的 `main()` 函数(关键修复) ```cpp #include <iostream> #include <queue> #include <string> #include <algorithm> // for remove_if using namespace std; // ... TreeNode 和 BinaryTree 类保持不变 ... int main() { string input; // 读取一整行,包括中间的空格 getline(cin, input); // 删除字符串中所有的空格 input.erase(remove_if(input.begin(), input.end(), ::isspace), input.end()); // 如果输入为空则退出 if (input.empty()) { return 1; } BinaryTree<char> tree(input); cout << "前序遍历序列" << tree.getPreOrder() << endl; cout << "中序遍历序列" << tree.getInOrder() << endl; cout << "后序遍历序列" << tree.getPostOrder() << endl; cout << "层序遍历序列" << tree.getLevelOrder() << endl; return 0; } ``` --- ### 🔧 示例说明 #### 输入: ``` A B # D # # C # # ``` 经过 `getline` + 去空格处理 → 得到: ``` AB#D##C## ``` ✅ 正确构建二叉树! --- ### 🌲 构造过程回顾 输入序列:`AB#D##C##` 递归建树步骤: 1. `A`:根 2. `B`:A 的左孩子 3. `#`:B 的左孩子为空 4. `D`:B 的右孩子 5. `#`:D 的左为空 6. `#`:D 的右为空 7. `C`:A 的右孩子 8. `#`:C 左为空 9. `#`:C 右为空 结构如下: ``` A / \ B C \ D ``` --- ### ✅ 正确输出: ``` 前序遍历序列ABDC 中序遍历序列BDAC 后序遍历序列DBCA 层序遍历序列ABCD ``` --- ### 💡 补充建议 如果你不能确定输入是否有空格,最稳妥的做法就是 **始终读整行去空格**。这能兼容两种输入格式: - `AB#D##C##` - `A B # D # # C # #` --- ### ✅ 最终完整修正点总结 | 问题 | 修正方法 | |------|----------| | 只读到第一个字符 `'A'` | 改用 `getline(cin, input)` | | 输入含空格导致建树错误 | 使用 `remove_if` 删除所有空白符 | | 输入格式不统一 | 统一预处理成紧凑字符串 | ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值