1. 二叉樹的建立與基本操作
阿新 • • 發佈:2018-12-18
1. 二叉樹的建立與基本操作
成績 | 10 | 開啟時間 | 2018年10月28日 星期日 18:00 |
折扣 | 0.8 | 折扣時間 | 2018年11月18日 星期日 23:55 |
允許遲交 | 否 | 關閉時間 | 2018年11月28日 星期三 23:55 |
編寫程式實現二叉樹的如下操作:
1) 建立二叉連結串列
2) 二叉樹的先序、中序、後序遍歷
3) 求二叉樹的葉子結點個數
4) 將二叉樹中所有結點的左、右子樹相互交換
輸入:
擴充套件二叉樹先序序列:ab#d##ce###。其中#代表空指標。
輸出:
二叉樹的凹入表示
二叉樹的先序序列、中序序列、後序序列
二叉樹葉子結點個數
左、右子樹相互交換後的二叉樹的凹入表示
左、右子樹相互交換後的二叉樹的先序序列、中序序列、後序序列。
說明:
在輸出凹入表示的二叉樹時,先輸出根結點,然後依次輸出左右子樹,上下層結點之間相隔 3 個空格。
#include<stdio.h> #include<stdlib.h> struct Btreenode { char element; struct Btreenode *left; struct Btreenode *right; }; typedef struct Btreenode *PtrNode; int numlef; void Creat_Btree(PtrNode*proot) //用二級指標建立二叉樹 { char c; c = getchar(); if (c == '#') *proot = NULL; else { (*proot) = (PtrNode)malloc(sizeof (struct Btreenode)); (*proot)->element = c; Creat_Btree(&(*proot)->left); Creat_Btree(&(*proot)->right); if (!(*proot)->left&&!(*proot)->right) numlef++; } } PtrNode creat_BTree(PtrNode proot) //用返回值建立二叉樹(沒用二級指標) { char c; c = getchar(); if (proot == NULL&&c!='#') { proot = (PtrNode)malloc(sizeof (struct Btreenode)); proot->element = c; proot->left = proot->right = NULL; proot->left = creat_BTree(proot->left); proot->right = creat_BTree(proot->right); if (!(proot)->left&&!(proot)->right) numlef++; } return proot; } void inorder(PtrNode rt) { if (rt) { inorder(rt->left); printf("%c", rt->element); inorder(rt->right); } } void preorder(PtrNode rt) { if (rt) { printf("%c", rt->element); preorder(rt->left); preorder(rt->right); } } void postorder(PtrNode rt) { if (rt) { postorder(rt->left); postorder(rt->right); printf("%c", rt->element); } } void Printline(char c, int num) { for (int i = 0; i < 4*num; i++) { printf(" "); } printf("%c\n", c); } void listtree(PtrNode rt, int depth) { if (rt) { Printline(rt->element, depth); listtree(rt->left, depth + 1); listtree(rt->right, depth + 1); } } void Swap(PtrNode rt) { if (rt) { if (rt->left||rt->right) { PtrNode tmp = rt->left; rt->left = rt->right; rt->right = tmp; if (rt->left) Swap(rt->left); if (rt->right) Swap(rt->right); } } } int main() { //freopen("1.txt","r", stdin); PtrNode root=NULL; printf("BiTree\n"); //Creat_Btree(&root); root=creat_BTree(root); listtree(root, 0); printf("pre_sequence : "); preorder(root); printf("\n"); printf("in_sequence : "); inorder(root); printf("\n"); printf("post_sequence : "); postorder(root); printf("\n"); printf("Number of leaf: %d\n", numlef); printf("BiTree swapped\n"); Swap(root); listtree(root, 0); printf("pre_sequence : "); preorder(root); printf("\n"); printf("in_sequence : "); inorder(root); printf("\n"); printf("post_sequence : "); postorder(root); printf("\n"); return 0; }