首页 > 编程语言 > 详细

C/C++ - 反转二叉树

时间:2018-03-15 18:28:52      阅读:248      评论:0      收藏:0      [点我收藏+]

  由上而下递归反转代码:

#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++ - 反转二叉树

原文:https://www.cnblogs.com/darkchii/p/8575240.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!