#include<iostream> #define MAX 10010 using namespace std; typedef struct BiTNode { char data; struct BiTNode *lchild,*rchild; }BiTNode,*Bitree; void CreatBitree(Bitree &T)//先序遍历建立二叉树 { char ch; cin >> ch; if(ch == '#') T = NULL; else { T = new BiTNode; T -> data = ch; CreatBitree(T -> lchild); CreatBitree(T -> rchild); } } Bitree CreatBitree(char *pre,char *in,int n)//已知前序序列和中序序列建立二叉树 {//三个参数从左到右分别为存放前序序列和中序序列的字符数组以及序列长度 Bitree T; int i; if(n <= 0) return NULL; T = new BiTNode; T -> data = pre[0]; for(i = 0;in[i] != pre[0]; i++); T -> lchild = CreatBitree(pre + 1,in,i); T -> rchild = CreatBitree(pre + 1 + i,in + 1 + i,n - i -1); return T; } Bitree Creatbitree(char *post,char *in,int n)//已知后序序列和中序序列建立二叉树 {//三个参数从左到右分别为存放后序序列和中序序列的字符数组以及序列长度 Bitree T; int i; if(n <= 0) return NULL; T = new BiTNode; T -> data = post[n - 1]; for(i = 0;in[i] != post[n - 1]; i++); T -> lchild = Creatbitree(post,in,i); T -> rchild = Creatbitree(post + i,in + 1 + i,n - i - 1); return T; } void Preorder(Bitree T)//先序遍历二叉树 { if(T) { cout << T -> data; Preorder(T -> lchild); Preorder(T -> rchild); } } void Inorder(Bitree T)//中序遍历二叉树 { if(T) { Inorder(T -> lchild); cout << T -> data; Inorder(T -> rchild); } } void Postorder(Bitree T)//后序遍历二叉树 { if(T) { Postorder(T -> lchild); Postorder(T -> rchild); cout << T -> data; } } void Exchange(Bitree &T)//交换二叉树 { Bitree temp; if(T) { temp = T -> lchild; T -> lchild = T -> rchild; T -> rchild = temp; Exchange(T -> lchild); Exchange(T -> rchild); } } void PreorderPrintLeaves( Bitree T)//先序输出叶结点 { if(T == NULL) return; if(T -> lchild == NULL && T -> rchild == NULL) cout << T -> data; PreorderPrintLeaves(T -> lchild); PreorderPrintLeaves(T -> rchild); } void Levelorder(Bitree T)//二叉树层次遍历 { int front = 0,rear = 0; struct BiTNode *queue[MAX]; if(T == NULL) return; queue[rear++] = T; while(rear != front) { T = queue[front++]; if(T -> lchild) queue[rear++] = T -> lchild; if(T -> rchild) queue[rear++] = T -> rchild; cout << T -> data; } } int NodeCount(Bitree T)//统计二叉树结点个数 { if(T == NULL) return 0; else return NodeCount(T -> lchild) + NodeCount(T -> rchild) + 1; } int LeafCount(Bitree T)//统计二叉树叶子节点个数 { int count; if(T == NULL) count = 0; else if(T -> lchild == NULL && T -> rchild == NULL) count = 1; else count = LeafCount(T -> lchild) + LeafCount(T -> rchild); return count; } int NodCount(Bitree T)//统计二叉树度为1的结点个数 { int count = 0; if(NULL != T) { if((T->lchild != NULL && T->rchild == NULL)||(T->rchild != NULL && T->lchild == NULL)) count = 1 + NodCount(T -> lchild) + NodCount(T -> rchild); else count = NodCount(T -> lchild) + NodCount(T -> rchild); } return count; } int Depth(Bitree T)//计算二叉树深度 { if(T == NULL) return 0; else return Depth(T -> lchild) > Depth(T -> rchild) ? Depth(T -> lchild) + 1 : Depth(T -> rchild) + 1; } int main() { return 0; }
二叉树操作集合
猜你喜欢
转载自blog.csdn.net/xiao__hei__hei/article/details/80260883
今日推荐
周排行