C++ 由后序和中序遍历确定二叉树

本文介绍了一种通过后序遍历和中序遍历序列构建二叉树的方法,并提供了完整的C++实现代码。文章详细解释了构建过程中的关键步骤,包括如何根据后序序列的最后一个元素确定根节点,以及如何划分左右子树序列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
解题思路
1.根据后序序列最后一个元素建立根节点;
2.在中序序列中找到该元素,确定根节点的左右子树序列;
3.在后序序列中确定左右子树的后序序列;
4.由左子树的中序和后序序列建立左子树;
5.由右子树的中序和后序序列建立右子树;
例子
7    //元素个数
2 3 1 5 7 6 4   //后序遍历序列
1 2 3 4 5 6 7   //中序遍历序列
取出后序序列最后一个元素4,将中序遍历分为 1 2 3 和 5 6 7两组
处理1 2 3,其后序序列为2 3 1
取出左子树的根1 将左子树分为 空 和右:2 3
……
实现代码如下
*/
#include <iostream>
#include <vector>
#include <queue>

using namespace std;
typedef struct TreeNode
{
    int data;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : data(x), left(NULL), right(NULL) {}
} * treeNode;
class Solution
{
public:
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder)
    {
        TreeNode *root = NULL;

        if (postorder.size() == 0)
            return NULL;

        int post_last = postorder.size() - 1;

        int loc = 0;

        while (postorder[post_last] != inorder[loc] && loc < inorder.size())
            loc++;

        root = new TreeNode(postorder[post_last]);
        //处理左子树
        vector<int> l_post(postorder.begin(), postorder.begin() + loc);
        vector<int> l_in(inorder.begin(), inorder.begin() + loc);
        root->left = buildTree(l_in, l_post);
        l_post.clear();
        l_in.clear();

        //处理右子树
        vector<int> r_post(postorder.begin() + loc, postorder.end() - 1);
        vector<int> r_in(inorder.begin() + loc + 1, inorder.end());
        root->right = buildTree(r_in, r_post);
        r_post.clear();
        r_in.clear();

        return root;
    }
//按层遍历输出
//思路:先将根入队列,判断其左右子树是否为空,不空,入队,继续该操作,从对头访问序列
    void levelOrder(TreeNode *root)
    {
        queue<TreeNode *> que;
        TreeNode *T = root;
        que.push(T);
        while (!que.empty())
        {
            T = que.front();
            cout << T->data << " ";
            que.pop();
            if (T->left)
                que.push(T->left);
            if (T->right)
                que.push(T->right);
        }
        cout << endl;
    }
};
int main()
{
    int n;
    cin >> n;
    vector<int> inorder(n);
    vector<int> postorder(n);

    for (int i = 0; i < n; i++)
        cin >> postorder[i];
    for (int i = 0; i < n; i++)
        cin >> inorder[i];
    Solution solution;
    TreeNode *root = solution.buildTree(inorder, postorder);
    solution.levelOrder(root);

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值