以二叉鏈表作為二叉樹的存儲結構,交換二叉樹中每個結點的左孩子和右孩子。
輸入格式:
輸入二叉樹的先序序列。
提示:一棵二叉樹的先序序列是一個字符串,若字符是‘#’,表示該二叉樹是空樹,否則該字符是相應結點的數據元素。
輸出格式:
輸出有兩行:
第一行是原二叉樹的中序遍歷序列;
第二行是交換后的二叉樹的中序遍歷序列。
輸入樣例:
ABC##DE#G##F###
輸出樣例:
CBEGDFA
AFDGEBC
代碼實現:
#include <stdio.h> #include <malloc.h> #include <string.h> typedef struct TreeNode *BinTree; struct TreeNode { char data; BinTree left, right; }; BinTree CreatBinTree(); //創建樹 void PreOrderTraversal( BinTree BT ); //中序遍歷 void change ( BinTree BT ); //交換根節點 int main(){ BinTree BT = CreatBinTree(); PreOrderTraversal(BT); printf("\n"); change ( BT ); PreOrderTraversal(BT); return 0; } BinTree CreatBinTree(){ //根據前序遍歷創建樹 BinTree BT; char str; scanf("%c", &str); if (str != '#'){ BT = (BinTree)malloc(sizeof(struct TreeNode)); BT->data = str; BT->left = CreatBinTree(); BT->right = CreatBinTree(); } else { BT = NULL; } return BT; } void change ( BinTree BT ){ //交換根節點(左右子樹不空) if (BT->right == NULL && BT->left == NULL){ return; } BinTree t; t = BT->left; BT->left = BT->right; BT->right = t; if (BT->left){ //往后掃描 change (BT->left); } if (BT->right){ change (BT->right); } } void PreOrderTraversal( BinTree BT ){ //中序遍歷 if (BT) { PreOrderTraversal (BT->left); printf("%c", BT->data); PreOrderTraversal (BT->right); } }