从给定的预序遍历构建二叉树

Build a binary tree from a given preorder traversal

本文关键字:遍历 构建 二叉树      更新时间:2023-10-16

我有一个存储在数组中的二叉树的预序遍历,我想基于这个遍历重新创建二叉树。我的数组看起来像这样:{NNNLLNLLNLNLNNLLNLL},其中N代表一个节点,L代表一个叶子。我想递归地执行此操作,但我在想出算法时遇到了麻烦。任何建议将不胜感激。

假设每个节点都有 2 或 0 个后代(满足此属性的树称为完整严格二叉树),这应该可以工作)

void create_from_traversal(Node* root, int& index) {
    if (traversal[index] == 'L') {
        root->left = root->right = NULL;
        return;
    }
    root->left = new Node();
    create_from_traversal(root->left, ++index);
    root->right = new Node();
    create_from_traversal(root->right, ++index);
}

带检查的完整示例:

#include <string>
#include <iostream>
class Node {
public:
    Node* left;
    Node* right;
};
std::string traversal = "NNNLLNLLNLNLNNLLNLL";
void create_from_traversal(Node* root, int& index) {
    if (traversal[index] == 'L') {
        root->left = root->right = NULL;
        return;
    }
    root->left = new Node();
    create_from_traversal(root->left, ++index);
    root->right = new Node();
    create_from_traversal(root->right, ++index);
}
void print_traversal(Node* root) {
    if (root->left == NULL) {
        std::cout << "L";
        return;
    }
    std::cout << "N";
    print_traversal(root->left);
    print_traversal(root->right);
}
int main() {
    Node* root = new Node();
    int index = 0;
    create_from_traversal(root, index);
    // Does it work?
    print_traversal(root); // Output should be equal to given traversal
    std::cout << std::endl;
}

输出:

NNNLLNLLNLNLNNLLNLL

重建树之前,还需要一次遍历。给定三者(前、后、入)中的任何两个遍历,您可以重建。但是只给定一个,不可能唯一地重建树。