二叉樹的鏡像—劍指offer
阿新 • • 發佈:2017-08-19
它的 stdio.h 頭插 bsp 二叉樹的鏡像 typedef print off close
題目:完成一個函數,輸入一個二叉樹,該函數輸出它的鏡像
1 #include<stdio.h> 2 #include<stdlib.h> 3 typedef struct node 4 { 5 char value; 6 struct node *lchild; 7 struct node *rchild; 8 }TreeNode,*Tree; 9 //頭插法創建二叉樹 10 Tree CreateTree(Tree &t) 11 { 12 char ch; 13 scanf_s("%c", &ch);View Code14 if (ch == ‘#‘) 15 t = NULL; 16 else 17 { 18 t = (Tree)malloc(sizeof(TreeNode)); 19 if (!t) 20 { 21 printf("分配內存出錯!"); 22 return NULL; 23 } 24 t->value = ch; 25 CreateTree(t->lchild); 26 CreateTree(t->rchild);27 } 28 return t; 29 } 30 //求二叉樹鏡像 31 void MirrorRecursively(Tree pNpde) 32 { 33 if (pNpde == NULL) 34 return ; 35 if (pNpde->lchild == NULL && pNpde->rchild == NULL) 36 return ; 37 Tree pTemp = pNpde->lchild; 38 pNpde->lchild = pNpde->rchild;39 pNpde->rchild = pTemp; 40 if (pNpde->lchild) 41 MirrorRecursively(pNpde->lchild); 42 if (pNpde->rchild) 43 MirrorRecursively(pNpde->rchild); 44 } 45 //先序遞歸遍歷 46 void PreOrder(Tree T) 47 { 48 if (T) 49 { 50 printf("%c",T->value); 51 PreOrder(T->lchild); 52 PreOrder(T->rchild); 53 } 54 } 55 int main() 56 { 57 Tree T; 58 printf("創建二叉樹,‘#’代表空:"); 59 CreateTree(T); 60 printf("先序遍歷二叉樹:"); 61 PreOrder(T); 62 MirrorRecursively(T); 63 if (T) 64 { 65 printf("\n先序遍歷鏡像二叉樹: "); 66 PreOrder(T); 67 } 68 else 69 printf("創建的樹為空"); 70 printf("\n"); 71 return 0; 72 } 73 /* 74 創建二叉樹,‘#’代表空:ABD##E##CF##G## 75 先序遍歷二叉樹:ABDECFG 76 先序遍歷鏡像二叉樹: ACGFBED 77 請按任意鍵繼續. . . 78 79 創建二叉樹,‘#’代表空:# 80 先序遍歷二叉樹:創建的樹為空 81 請按任意鍵繼續. . . 82 83 */
二叉樹的鏡像—劍指offer