由上而下递归反转代码:
#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; }
没什么好解释的。