以下是使用C语言编写的程序,实现了建立静态链表存储的二叉树,并输出其先序遍历、中序遍历和后序遍历的序列。

#include <stdio.h>

const int MAXN = 100010;  /// 最大节点个数

typedef struct _binary_treeNode {
    int  data;   /// 数据域
    int  left;   /// 左孩子所在的下标,-1 表示无左子树
    int  right;  /// 右孩子所在的下标,-1 表示无右子树
} BiTree;

BiTree t[MAXN];
unsigned n;  /// 实际节点个数

void preorderTraversal(int root) {
    if (root == -1) {
        return;
    }
    
    printf('%d ', t[root].data);
    preorderTraversal(t[root].left);
    preorderTraversal(t[root].right);
}

void inorderTraversal(int root) {
    if (root == -1) {
        return;
    }
    
    inorderTraversal(t[root].left);
    printf('%d ', t[root].data);
    inorderTraversal(t[root].right);
}

void postorderTraversal(int root) {
    if (root == -1) {
        return;
    }
    
    postorderTraversal(t[root].left);
    postorderTraversal(t[root].right);
    printf('%d ', t[root].data);
}

int main() {
    scanf('%u', &n);
    
    for (unsigned i = 0; i < n; i++) {
        scanf('%d', &(t[i].data));
        scanf('%d', &(t[i].left));
        scanf('%d', &(t[i].right));
    }
    
    preorderTraversal(0);
    printf('\n');
    
inorderTraversal(0);
    printf('\n');
    
    postorderTraversal(0);
    printf('\n');
    
    return 0;
}

注意:以上代码假设输入的二叉树中的节点数据都是非负整数,并且空节点用-1表示。程序通过先序遍历序列构建二叉树,并输出其先序遍历、中序遍历和后序遍历的序列。使用gcc命令进行编译。

二叉树 - 建树 - 遍历 - 静态链表存储方式

原文地址: https://www.cveoy.top/t/topic/SvD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录