二叉树的建立与基本操作(C++语言)

编写程序实现二叉树的如下操作:
1) 建立二叉链表
2) 二叉树的先序、中序、后序遍历
3) 求二叉树的叶子结点个数
4) 将二叉树中所有结点的左、右子树相互交换

输入:
  扩展二叉树先序序列:ab#d##ce###。其中#代表空指针。

输出:
  二叉树的凹入表示
  二叉树的先序序列、中序序列、后序序列
  二叉树叶子结点个数
  左、右子树相互交换后的二叉树的凹入表示
  左、右子树相互交换后的二叉树的先序序列、中序序列、后序序列。

说明:
  在输出凹入表示的二叉树时,先输出根结点,然后依次输出左右子树,上下层结点之间相隔 3 个空格。


样例

输入(1)

ab#d##ce###

输出(1)

BiTree
a
    b
        d
    c
        e
pre_sequence  : abdce
in_sequence   : bdaec
post_sequence : dbeca
Number of leaf: 2
BiTree swapped
a
    c
        e
    b
        d
pre_sequence  : acebd
in_sequence   : ceadb
post_sequence : ecdba

输入(2)

abd##e##cf##g##

输出(2)

BiTree
a
    b
        d
        e
    c
        f
        g
pre_sequence  : abdecfg
in_sequence   : dbeafcg
post_sequence : debfgca
Number of leaf: 4
BiTree swapped
a
    c
        g
        f
    b
        e
        d
pre_sequence  : acgfbed
in_sequence   : gcfaebd
post_sequence : gfcedba

代码

#include <cstdio>
#include <iostream>
#include <queue>
#include <cstring>
#include <cstdlib>
#include <algorithm>
using namespace std;

// Binary tree storage structure
typedef struct BiTNode {
    char data;
    struct BiTNode* lchild;
    struct BiTNode* rchild;
} BiTNode, *BiTree;

queue<BiTree> q; // Auxiliary queue
int counts = 0; // Count of leaf nodes

void createBiTree();       // Build the binary tree
void visit(BiTree R);      // Visit a node
void print(BiTree R, int n); // Output the binary tree
void pre_sequence(BiTree R);    // Pre-order traversal
void in_sequence(BiTree R);     // In-order traversal
void post_sequence(BiTree R);   // Post-order traversal
/* Representations after swapping left and right subtrees */
void swap_print(BiTree R, int n);
void swap_pre_sequence(BiTree R);
void swap_in_sequence(BiTree R);
void swap_post_sequence(BiTree R);

int main() {
    BiTree bit;
    bit = (BiTree)malloc(sizeof(BiTNode));
    q.push(bit);

    // Build the tree
    createBiTree();

    // Print the binary tree
    cout << "BiTree" << endl;
    print(bit, 0);

    // Pre-order
    cout << "pre_sequence  : ";
    pre_sequence(bit);
    cout << endl;

    // In-order
    cout << "in_sequence   : ";
    in_sequence(bit);
    cout << endl;

    // Post-order
    cout << "post_sequence : ";
    post_sequence(bit);
    cout << endl;

    // Number of leaf nodes
    cout << "Number of leaf: " << counts << endl;

    /* Swap the subtrees */
    cout << "BiTree swapped" << endl;
    swap_print(bit, 0);

    cout << "pre_sequence  : ";
    swap_pre_sequence(bit);
    cout << endl;

    cout << "in_sequence   : ";
    swap_in_sequence(bit);
    cout << endl;

    cout << "post_sequence : ";
    swap_post_sequence(bit);
    cout << endl;

    return 0;
}

void createBiTree() {
    char c;
    BiTree T, N;
    while (!q.empty()) {
        cin >> c;
        if (c == '\n') // End reading at a newline character
            break;

        T = q.front();
        q.pop();
        T->data = c; // Assign node value

        if (c != '#') {
            // Build the left subtree
            N = (BiTree)malloc(sizeof(BiTNode));
            T->lchild = N;
            q.push(N);
            createBiTree();
            // Build the right subtree
            N = (BiTree)malloc(sizeof(BiTNode));
            T->rchild = N;
            q.push(N);
            createBiTree();
        }
    }
}

void visit(BiTree R) {
    // Output the node if it's not empty
    if (R->data != '#' && R->data != '\0')
        cout << R->data;
}

void print(BiTree R, int n) {
    if (R->data != '#' && R->data != '\0') {
        int i = 1;
        while (i <= n) {
            cout << "    ";
            i++;
        }
        visit(R);
        cout << endl;

        // Traverse one level down
        n++;
        print(R->lchild, n);
        print(R->rchild, n);
    }
}

void pre_sequence(BiTree R) {
    if (R->data != '#' && R->data != '\0') {
        visit(R);
        pre_sequence(R->lchild);
        pre_sequence(R->rchild);
    }
}

void in_sequence(BiTree R) {
    if (R->data != '#' && R->data != '\0') {
        in_sequence(R->lchild);

        /* Count leaf nodes in combination with in-order traversal */
        if ((R->lchild->data == '#' || R->lchild->data == '\0') && (R->rchild->data == '#' || R->rchild->data == '\0'))
            counts++;

        visit(R);
        in_sequence(R->rchild);
    }
}

void post_sequence(BiTree R) {
    if (R->data != '#' && R->data != '\0') {
        post_sequence(R->lchild);
        post_sequence(R->rchild);
        visit(R);
    }
}

void swap_print(BiTree R, int n) {
    // The representation after swapping is the same as the original, just in a different order
    if (R->data != '#' && R->data != '\0') {
        int i = 1;
        while (i <= n) {
            cout << "    ";
            i++;
        }
        visit(R);
        cout << endl;

        n++;
        swap_print(R->rchild, n);
        swap_print(R->lchild, n);
    }
}

void swap_pre_sequence(BiTree R) {
    if (R->data != '#' && R->data != '\0') {
        visit(R);
        swap_pre_sequence(R->rchild);
        swap_pre_sequence(R->lchild);
    }
}

void swap_in_sequence(BiTree R) {
    if (R->data != '#' && R->data != '\0') {
        swap_in_sequence(R->rchild);
        visit(R);
        swap_in_sequence(R->lchild);
    }
}

void swap_post_sequence(BiTree R) {
    if (R->data != '#' && R->data != '\0') {
        swap_post_sequence(R->rchild);
        swap_post_sequence(R->lchild);
        visit(R);
    }
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用二叉树来实现字典树,以下是用C++语言编写的一个示例代码: ```cpp #include <iostream> using namespace std; const int ALPHABET_SIZE = 26; struct TrieNode { TrieNode* children[ALPHABET_SIZE]; bool isEndOfWord; }; TrieNode* createNode() { TrieNode* newNode = new TrieNode; newNode->isEndOfWord = false; for (int i = 0; i < ALPHABET_SIZE; i++) { newNode->children[i] = NULL; } return newNode; } void insert(TrieNode* root, string word) { TrieNode* cur = root; for (int i = 0; i < word.length(); i++) { int index = word[i] - 'a'; if (cur->children[index] == NULL) { cur->children[index] = createNode(); } cur = cur->children[index]; } cur->isEndOfWord = true; } bool search(TrieNode* root, string word) { TrieNode* cur = root; for (int i = 0; i < word.length(); i++) { int index = word[i] - 'a'; if (cur->children[index] == NULL) { return false; } cur = cur->children[index]; } return (cur != NULL && cur->isEndOfWord); } int main() { TrieNode* root = createNode(); insert(root, "apple"); insert(root, "banana"); insert(root, "cherry"); cout << "Searching for 'apple': " << (search(root, "apple") ? "Found" : "Not Found") << endl; cout << "Searching for 'banana': " << (search(root, "banana") ? "Found" : "Not Found") << endl; cout << "Searching for 'cherry': " << (search(root, "cherry") ? "Found" : "Not Found") << endl; cout << "Searching for 'grape': " << (search(root, "grape") ? "Found" : "Not Found") << endl; return 0; } ``` 这段代码演示了如何使用二叉树实现字典树的插入和搜索操作。首先,我们创建了一个TrieNode结构体,其中包含一个布尔型变量`isEndOfWord`用于标记单词的结尾,以及一个包含26个子节点的数组`children`,用于存储每个字母的子节点。 然后,我们定义了一些辅助函数。`createNode`函数用于创建新的节点,`insert`函数用于将单词插入字典树,`search`函数用于搜索字典树中是否存在某个单词。 在主函数中,我们创建了一个空的字典树,并插入了几个单词。然后,我们通过调用`search`函数来搜索特定的单词,并输出搜索结果。 注意:这只是一个简单的示例代码,实际应用中可能需要考虑更多的功能和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值