1. 程式人生 > >C/C++ - 反轉二叉樹

C/C++ - 反轉二叉樹

creat root type eat highlight scan lib return + -

  由上而下遞歸反轉代碼:

#include <stdio.h>
#include <stdlib.h>

typedef struct Tree {
    int val;
    struct Tree* left;
    struct Tree* right;
}Tree;

void CreateBiTree(Tree**T)
{
    int val;

    scanf("%d", &val);
    if(val == -1)
        *T = NULL;
    else
    {
        *T = (Tree *)malloc(sizeof(Tree));
        (*T)->val = val;
        CreateBiTree(&(*T)->left);
        CreateBiTree(&(*T)->right);
    }
}

void ExchangeLeftRight(Tree **root)
{
    Tree * node = (*root)->right;
    (*root)->right = (*root)->left;
    (*root)->left = node;
}

void RecursiveReversal(Tree *root) //反轉二叉樹
{
    if (root != NULL)
    {
        ExchangeLeftRight(&root);
        RecursiveReversal(root->left);
        RecursiveReversal(root->right);
    }
}

void Print(Tree*root)
{
    if (root != NULL)
    {
        Print(root->left);
        printf("%d ", root->val);
        Print(root->right);
    }
}

int main()
{
    Tree* root;

    CreateBiTree(&root);
    Print(root);
    printf("\n");
    RecursiveReversal(root);
    Print(root);

    return 0;
}

  沒什麽好解釋的。

C/C++ - 反轉二叉樹