数据结构森林的遍历(先序遍历和中序遍历)C语言代码

时间:2024-10-13 21:56:11
// 定义树节点结构  
typedef struct TreeNode {
    int val;
    struct TreeNode* left;
    struct TreeNode* right;
} TreeNode;
// 创建新节点  
TreeNode* createNode(int val) {
    TreeNode* newNode = (TreeNode*)malloc(sizeof(TreeNode));
    newNode->val = val;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}
//前序遍历
void preOrderTraversal(TreeNode* root)
{
    if (root!=NULL)
    {
        printf("%d ", root->val);
        preOrderTraversal(root->left);
        preOrderTraversal(root->right);
    }
}
void preOrderForestTraversal(TreeNode** forest, int numTrees)
{
    for (int i = 0; i < numTrees; i++)
    {
        preOrderTraversal(forest[i]);
    }
}
//中序遍历
void inOrderTraversal(TreeNode* root)
{
    if (root!=NULL)
    {
        inOrderTraversal(root->left);
        printf("%d ", root->val);
        inOrderTraversal(root->right);
    }
}
void inOrderForestTraversal(TreeNode** forest, int numTrees)
{
    for (int i = 0; i < numTrees; i++)
    {
        inOrderTraversal(forest[i]);
    }
}
int main()
{
    TreeNode* tree1 = createNode(1);
    tree1->left = createNode(2);
    tree1->right = createNode(3);
    tree1->left->left = createNode(4);
    tree1->left->right = createNode(5);

    TreeNode* tree2 = createNode(6);
    tree2->left = createNode(7);
    tree2->right = createNode(8);

    TreeNode* forest[2] = { tree1,tree2 };//森林组合
    int numTrees = 2;

    printf("先序遍历森林\n");
    preOrderForestTraversal(forest, numTrees);
    printf("\n");
    printf("中序遍历森林\n");
    inOrderForestTraversal(forest, numTrees);

}