binary tree(basic operation)

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值