#include<stdio.h> #include<stdlib.h> //二叉树的链式存储 typedef struct BiNode{ int data; struct BiNode *lchild,*rchild; }BiNode,*BiTree; //定义一棵树 BiTree root = NULL; void Visit(BiNode *N){ printf("%d\n",N->data); } void PreOrder(BiTree T){ if(T != NULL){ Visit(T); PreOrder(T->lchild); PreOrder(T->rchild); } } //中序遍历 void InOrder(BiTree T){ if(T != NULL){ PreOrder(T->lchild); Visit(T); PreOrder(T->rchild); } } //后序遍历 void PosteOrder(BiTree T){ if(T != NULL){ PreOrder(T->lchild); PreOrder(T->rchild); Visit(T); } } //求树的深度 int TreeDepth(BiTree T){ if(T == NULL){ return 0; } else{ int l = TreeDepth(T->lchild); int r = TreeDepth(T->rchild); return l > r ? l+1 : r+1; } } int main(){ BiTree root = (BiTree)malloc(sizeof(BiTree)); root->data = 1; root->lchild = NULL; root->rchild = NULL; BiNode *p = (BiNode *)malloc(sizeof(BiNode)); p->data = 2; p-> lchild = NULL; p-> rchild = NULL; root->lchild = p; BiNode *q = (BiNode*)malloc(sizeof(BiNode)); q ->data = 3; q->lchild = NULL; q->rchild = NULL; root->rchild = q; PreOrder(root); InOrder(root); PosteOrder(root); printf("The tree's depth id %d!\n",TreeDepth(root)); return 0; }
树的基本定义和遍历
最新推荐文章于 2023-05-17 20:48:04 发布