算法——层序遍历和中序遍历构造二叉树

晴问 通过中序遍历判断左右子树,接着从层序遍历中,把左子树的层序遍历和右子树的层序遍历提取出来

cpp 复制代码
#include <bits/stdc++.h>

using namespace std;

vector<int> in, cc;

struct treeNode {
    int data;
    treeNode *left;
    treeNode *right;

    treeNode(int data) : data(data), left(nullptr), right(nullptr) {}
};


treeNode *dfs(treeNode *&root, vector<int> &level, int in_left, int in_right) {
    if (level.size() == 0) return nullptr;
    int curRootNum = level[0], rootInIndex;
    for (rootInIndex = in_left; rootInIndex <= in_right; ++rootInIndex) {
        if (in[rootInIndex] == curRootNum) break;
    }

    root = new treeNode(curRootNum);

    set<int> leftTree;
    for (int i = in_left; i < rootInIndex; ++i) {
        leftTree.insert(in[i]);
    }

    vector<int> level_left, level_right;
    for (int i = 0; i < level.size(); ++i) {
        if (level[i] == curRootNum) continue;
        if (leftTree.find(level[i]) != leftTree.end()) {
            level_left.push_back(level[i]);
        } else {
            level_right.push_back(level[i]);
        }
    }

    dfs(root->left, level_left, in_left, rootInIndex - 1);
    dfs(root->right, level_right, rootInIndex + 1, in_right);

    return root;
}

vector<int> result;

void preOrder(treeNode *root) {
    if (root == nullptr) return;

    result.push_back(root->data);
    preOrder(root->left);
    preOrder(root->right);
}

int main() {

    int n;
    cin >> n;
    for (int i = 0; i < n; ++i) {
        int num;
        cin >> num;
        cc.push_back(num);
    }
    for (int i = 0; i < n; ++i) {
        int num;
        cin >> num;
        in.push_back(num);
    }

    treeNode *root;
    dfs(root, cc, 0, n - 1);

    preOrder(root);

    for (int i = 0; i < result.size(); ++i) {
        cout << result[i];
        if (i != result.size() - 1) cout << " ";
    }
    return 0;
}
相关推荐
m0_626535202 分钟前
力扣题目练习 换水问题
python·算法·leetcode
第六五4 分钟前
DPC和DPC-KNN算法
人工智能·算法·机器学习
一匹电信狗5 分钟前
【LeetCode_160】相交链表
c语言·开发语言·数据结构·c++·算法·leetcode·stl
Java技术实践26 分钟前
JPA 用 List 入参在 @Query中报错 unexpected AST node: {vector}
数据结构·windows·list
陌路2026 分钟前
S4双向链表
数据结构·链表
再卷也是菜1 小时前
C++篇(14)二叉树进阶算法题
c++·算法
小邓儿◑.◑1 小时前
贪心算法 | 每周8题(三)
算法·贪心算法
2401_841495641 小时前
【数据结构】最长的最短路径的求解
java·数据结构·c++·python·算法·最短路径·图搜索
泡沫冰@1 小时前
数据结构(5)
数据结构
小龙报1 小时前
《算法每日一题(1)--- 连续因子》
c语言·开发语言·c++·windows·git·算法·visual studio