Exercises finishing binary tree (a)

A topic

Write a recursive algorithm, located in the binary tree of nodes which seek to sequence the sequence of the k-th position

thought

Order to declare a count preorder, each traversing a node order + 1, and then determines whether or not k is equal order, will equal the value range assigned to node e

Code

Status T641(BiTree T,TElemType *e, int *order,int k)
{
	if(T)
	{
		(*order)++;
		if(*order==k)
		{
			*e=T->data;
			return OK;
		}
		else
		{
			if(T641(T->lchild,e,order,k))
				return OK;
			if(T641(T->rchild,e,order,k))
				return OK;
		}
	}
	return ERROR;
}

Topic two

Write a recursive algorithm to calculate the number of leaf nodes in the binary tree

thought

It features leaf node is not a child node, then the binary tree may be traversed node judges whether each condition is satisfied plus one; preorder this recursive code segment.

Code

Status T642(BiTree T)
{
	int count=0;
	if(T)
	{
		if(T->lchild==NULL&&T->rchild==NULL)
			count++;
		else
		{
			count+=T642(T->lchild);
			count+=T642(T->rchild);
		}
	}
	return count;
}

Topic three

Write a recursive algorithm, the binary tree left and right subtrees of all nodes exchange

thought

The code is very simple, do not do too much to explain

Code

void T643(BiTree T)
{
	BiTree p;
	if(T)
	{
		p=T->lchild;
		T->lchild=T->rchild;
		T->rchild=p;
		T643(T->lchild);
		T643(T->rchild);
	}
	
Published 73 original articles · won praise 20 · views 4474

Guess you like

Origin blog.csdn.net/lzl980111/article/details/103017208