/** @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 node
bt = 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;
}