【考研03】二叉树递归遍历

1. 先序遍历

void preOrder(BTNode *p)
{
	if(p != NULL)
	{
		Visit(p);
		preOrder(p->lchild);
		preOrder(p->rchild);
	}
}

2. 中序遍历

void inOrder(BTNode *p)
{
	if(p != NULL)
	{
		inOrder(p->lchild);
		Visit(p);
		inOrder(p->rchild);
	}
}

3. 后序遍历

void postOrder(BTNode *p)
{
	if(p != NULL)
	{
		postOrder(p->lchild);
		postOrder(p->rchild);
		Visit(p);
	}
}

4. 求表达式值【后序遍历】

int comp(BTNode *p)
{
	int A,B;
	if(p != NULL)
	{
		if(p->lchild != NULL && p->rchild != NULL)
		{
			A = comp(p->lchild);
			B = comp(p->rchild);
			return op(A,B,p->data);
		}
		else
			return p->data-'0';
	}
	else
		return 0;
}

5. 求二叉树的深度【后序遍历】

int getDepth(BTNode *p)
{
	int LD,RD;
	if(p == NULL)
		return 0;  //如果是空树,则返回0
	else
	{
		LD = getDepth(p->lchild);
		RD = getDepth(p->rchild);
		return (LD>RD?LD:RD) + 1;
	}
}

6. 根据前序[1…n],中序[1…n]建立二叉树

BTNode *preInCreate(int A[],int B[],int l1,int h1,int l2,int h2)
{ //初始l1=l2=1,h1=h2=n
	BTNode root = (BTNode*)malloc(sizeof(BTNode));
	root->data = A[l1];
	for(i=l2;B[i]!=root->data;i++);
	int llen = i-l2;
	int rlen = h2-i;
	if(llen > 0)
		root->lchild = preInCreate(A,B,l1+1,l1+llen,l2,l2+llen-1);
	else
		root->lchild = NULL;
	if(rlen > 0)
		root->rchild = preInCreate(A,B,l1+len+1,h1,l2+len+1,h2);
	else
		root->rchild = NULL;
	return root;
}

7. 将二叉树转换为等价的中缀表达式【中序遍历】

typedef struct node
{
	char data[10];
	struct node *left,*right;
}BTree;
void BtreeToE(BTree *root)
{
	BtreeToExp(root,1);  //根的高度为1
}
void BtreeToExp(BTree *root,int deep)
{
	if(root == NULL)
		return;
	else if(root->left == NULL && root->right == NULL)
		printf("%s",root->data);
	else
	{
		if(deep>1)
			printf("(");
		BtreeToExp(root->left,deep+1);
		printf("%s",root->data);
		BtreeToExp(root->right,deep+1);
		if(deep>1)
			printf(")");
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值