binary tree(basic operation)
来源:互联网 发布:网络推广年度计划 编辑:程序博客网 时间:2024/06/05 04:32
/** @author: yj * time: 2012/4 * usage: basic function for binary tree */ #include "tree.h"#include <stdio.h>#include <stdlib.h>/** create binary tree parameters: none return: head of binary tree */node_t *creBinaryTree(){char data;node_t *bt;scanf("%c", &data);getchar();if(data == 'o') //o mean null nodebt = NULL;else{bt = (node_t *)malloc(sizeof(node_t));bt->data = data;bt->lchild = creBinaryTree();bt->rchild = creBinaryTree();}return bt;}/** recursive 递归遍历 binary tree **/void preorder(node_t *bt) //先序(preorder) head -> left child ->right child{if(NULL != bt){printf("%c\t", bt->data);preorder(bt->lchild);preorder(bt->rchild);}}void inorder(node_t *bt) //中序(inorder) left child -> head ->right child{if(NULL != bt){inorder(bt->lchild);printf("%c\t", bt->data);inorder(bt->rchild);}}void postorder(node_t *bt) //后序(postorder) left child -> right child -> head{if(NULL != bt){postorder(bt->lchild);postorder(bt->rchild);printf("%c\t", bt->data);}}/* count leaf nodes */int countLeaf(node_t *bt){static int n;if(bt != NULL){if((bt->lchild == NULL) && (bt->rchild) == NULL)n++;n = countLeaf(bt->lchild);n = countLeaf(bt->rchild);}return n;}/* get depth of tree */int getTreeDepth(node_t *bt){ int h, lh, rh;if(bt == NULL)h=0;else{lh = getTreeDepth(bt->lchild);lh = getTreeDepth(bt->rchild);h = lh > rh ? lh + 1 : rh + 1;}return h;}