关于#c++#的问题,请各位专家解答!

img

请问这咋答啊,二叉树的前中后序
有先序中序求后序
麻烦大家快点这是上课* *。

前:DCBFHGAE
中:BCHFGDAE
后:BHGFCEAD
第二题:

img

望采纳

第一题:根据描述,该二叉树的结构如下:

      D
     / \
    C   A
   /   /
  B   E
   \
    F
   / \
  H   G

则该二叉树的三种遍历结果如下:

先序遍历:D C B F H G A E

中序遍历:B C F H G D E A

后序遍历:B H G F C E A D

第二题:4258639761

该回答引用ChatGPT
可以通过递归的方式来实现先序中序求后序。

具体思路如下:

  1. 先序遍历的第一个节点为根节点,找到该节点在中序遍历中的位置,将中序遍历分为左子树和右子树。

  2. 根据左子树和右子树的节点数,将先序遍历分为左子树和右子树。

  3. 递归地对左子树和右子树进行步骤1和步骤2,直到只剩下一个节点。

  4. 后序遍历的最后一个节点为根节点,将左子树的后序遍历和右子树的后序遍历拼接起来,再将根节点加入到末尾即可。

下面是C++代码实现:

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

vector<int> postorder(vector<int>& preorder, vector<int>& inorder) {
    if (preorder.empty() || inorder.empty()) return {};
    int root_val = preorder[0];
    vector<int> postorder_left, postorder_right;
    vector<int> inorder_left, inorder_right;
    int i = 0;
    for (; i < inorder.size(); i++) {
        if (inorder[i] == root_val) break;
        inorder_left.push_back(inorder[i]);
    }
    for (int j = i + 1; j < inorder.size(); j++) {
        inorder_right.push_back(inorder[j]);
    }
    for (int j = 1; j < preorder.size(); j++) {
        if (j <= inorder_left.size()) {
            postorder_left.push_back(preorder[j]);
        } else {
            postorder_right.push_back(preorder[j]);
        }
    }
    vector<int> res_left = postorder(postorder_left, inorder_left);
    vector<int> res_right = postorder(postorder_right, inorder_right);
    res_left.insert(res_left.end(), res_right.begin(), res_right.end());
    res_left.push_back(root_val);
    return res_left;
}

int main() {
    vector<int> preorder = {1, 2, 4, 5, 3, 6, 7};
    vector<int> inorder = {4, 2, 5, 1, 6, 3, 7};
    vector<int> postorder_res = postorder(preorder, inorder);
    for (int i = 0; i < postorder_res.size(); i++) {
        cout << postorder_res[i] << " ";
    }
    cout << endl;
    return 0;
}

输出结果为:4 5 2 6 7 3 1