二叉树基本操作

xiaoxiao2025-08-13  28

#include<stdio.h> #include<stdlib.h> typedef char ElemType; typedef struct BinaryTreeNode{ ElemType data; struct BinaryTreeNode *lChild, *rChild; }BinaryTreeNode; typedef BinaryTreeNode* BiTree; BinaryTreeNode * PreCreateBt(BiTree &t)//先序创建二叉树 { char ch; ch=getchar(); if(ch=='#')//输入为#表示这里建立空二叉树,即遍历算法的空操作 { t=NULL; } else { t=(BinaryTreeNode *)malloc(sizeof(BinaryTreeNode)); t->data=ch; //构造根节点 PreCreateBt(t->lChild); //构造左子树 PreCreateBt(t->rChild); //构造右子树 } } void PreOrderTransverse(BiTree t)//先序遍历 { if(t==NULL) return; printf("%c",t->data);//打印输出根节点 PreOrderTransverse(t->lChild);// 然后先序遍历左子树 PreOrderTransverse(t->rChild);//然后先序遍历右子树 } int LeafCount(BiTree t) { if(t==NULL) return 0; if(t->lChild==NULL&&t->rChild==NULL) { return 1; } else { return LeafCount(t->lChild)+LeafCount(t->rChild); } } int CountAll(BiTree t) { if(t==NULL) return 0; return CountAll(t->lChild)+CountAll(t->rChild)+1; } int Depth(BiTree t) { if(t==NULL) return 0; else { int depthLeft=Depth(t->lChild), depthRight=Depth(t->rChild); return 1+(depthLeft>depthRight?depthLeft:depthRight); } } int main() { BiTree t; printf("请输入相应数据:\n"); PreCreateBt(t); printf("先序遍历:\n"); PreOrderTransverse(t); printf("\n叶子结点的个数:\n"); printf("%d",LeafCount(t)); printf("\n结点总数:\n"); printf("%d",CountAll(t)); printf("\n二叉树深度:\n"); printf("%d",Depth(t)); return 0; }
转载请注明原文地址: https://www.6miu.com/read-5034772.html

最新回复(0)