二叉树的遍历及求其深度
#include <stdio.h> #include <stdlib.h> typedef struct btnode { int data; struct btnode *lchild,*rchild; }btnode,*btree; //建立二叉树 btree createtree() { btree T; char p; p=getchar(); if (p=='#') T=NULL; else { T=(btree)malloc(sizeof(btnode)); T->data=p; T->lchild=createtree(); T->rchild=createtree(); } return T; } //按先序遍历 void preorder(btree root) { if (root!=NULL) { printf("%c",root->data); preorder(root->lchild); preorder(root->rchild); } } void inorder(btree root) { if (root!=NULL) { inorder(root->lchild); printf("%c",root->data); inorder(root->rchild); } } void postorder(btree root) { if (root!=NULL) { postorder(root->lchild); postorder(root->rchild); printf ("%c",root->data); } } int depth(btree t) { if (t==NULL) return 0; else { int h1,h2,h; h1=depth(t->lchild); h2=depth(t->rchild); if (h1>h2) h=h1+1; else h=h2+1; return h; } } int main() { btree t; t=createtree(); printf("输入二叉树的先序排列(空的地方输入#):"); printf("按先序遍历二叉树\n"); preorder(t); printf ("\n"); printf("按中序遍历二叉树\n"); inorder(t); printf ("\n"); printf("按后序遍历二叉树\n"); postorder(t); printf ("\n"); printf ("树的深度\n"); printf ("%d\n",depth(t)); return 0; }