主要是二叉树和树
求先序序列中第K个位置的结点的值
展开#include <stdio.h> #include <stdlib.h> typedef char TElemType; typedef struct BiTNode { TElemType data; struct BiTNode *lchild,*rchild; }BiTNode ,*BiTree; void CreateBiTree(BiTree *T) { char data; scanf("%c",&data); if(data=='#') *T=NULL; else { *T=(BiTree)malloc(sizeof(BiTNode)); (*T)->data=data; CreateBiTree(&((*T)->lchild)); CreateBiTree(&((*T)->rchild)); } } void printBiTree(BiTree T) { if(T) { printf("%c",T->data); } } void Preorder(BiTree T,void (*visit)(BiTree)) { if(T) { visit(T); Preorder(T->lchild,visit); Preorder(T->rchild,visit); } } void Preorder2(BiTree T,void (*visit)(BiTree),int *k) { if(T) { (*k)--; if(*k) { Preorder2(T->lchild,visit,k); Preorder2(T->rchild,visit,k); } else { visit(T); } } } void main() { BiTree T; int k; void *pt=printBiTree; printf("输入二叉树序列:"); CreateBiTree(&T); printf("先序遍历:"); Preorder(T,pt); printf("\n"); printf("输入要输出的第K个位置:"); scanf("%d",&k); printf("输出先序序列的第%d个位置的结点的值:",k); Preorder2(T,pt,&k); printf("\n"); }
计算二叉树中叶子结点的数目
展开#include <stdio.h> #include <stdlib.h> typedef char ElemType; typedef struct TNode { ElemType data; struct TNode *lchild,*rchild; }TNode,*BiTree; void createBiTree(BiTree *T) { ElemType data; scanf("%c",&data); if(data!='#') { *T=(TNode *)malloc(sizeof(TNode)); (*T)->data=data; createBiTree(&((*T)->lchild)); createBiTree(&((*T)->rchild)); } else { *T=NULL; } } void Preorder(BiTree T,void (*visit)(BiTree),int *leafnodes ) { if(T) { visit(T); if(!T->lchild && !T->rchild) (*leafnodes)++; Preorder(T->lchild,visit,leafnodes); Preorder(T->rchild,visit,leafnodes); } } void printBiTree(BiTree T) { if(T) { printf("%c",T->data); } } void main() { BiTree T; int leafnodes=0; void *pt=printBiTree; printf("建树:"); createBiTree(&T); printf("先序遍历:"); Preorder(T,pt,&leafnodes); printf("\n"); printf("叶子结点总数:%d\n",leafnodes); }