6-6 Level-order Traversal

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Authur520/article/details/84886802

Write a routine to list out the nodes of a binary tree in "level-order". List the root, then nodes at depth 1, followed by nodes at depth 2, and so on. You must do this in linear time.

Format of functions:

void Level_order ( Tree T, void (*visit)(Tree ThisNode) );

where void (*visit)(Tree ThisNode) is a function that handles ThisNode being visited by Level_order, and Tree is defined as the following:

typedef struct TreeNode *Tree;
struct TreeNode {
    ElementType Element;
    Tree  Left;
    Tree  Right;
};

Sample program of judge:

#include <stdio.h>
#include <stdlib.h>

#define MaxTree 10 /* maximum number of nodes in a tree */
typedef int ElementType;

typedef struct TreeNode *Tree;
struct TreeNode {
    ElementType Element;
    Tree  Left;
    Tree  Right;
};

Tree BuildTree(); /* details omitted */
void PrintNode( Tree NodePtr )
{
   printf(" %d", NodePtr->Element);
}

void Level_order ( Tree T, void (*visit)(Tree ThisNode) );

int main()
{
    Tree T = BuildTree();
    printf("Level-order:");
    Level_order(T, PrintNode);
    return 0;
}

/* Your function will be put here */

Sample Output (for the tree shown in the figure):

Level-order: 3 5 6 1 8 10 9

代码实现为:

void Level_order ( Tree T, void (*visit)(Tree ThisNode) )
{
	Tree s[1000];  //树结点指针队列 
	int head = 0,tail = 0; //队列头尾指针 
	
	if( T )  s[tail++] = T;  //根结点存在,入队 
	while(head < tail){/*队列不为空时*/ 
		if(s[head]->Left)  s[tail++] = s[head]->Left;    //如果根结点左孩子存在,则入队 
		if(s[head]->Right) s[tail++] = s[head]->Right;
		(*visit)(s[head++]);  //访问队列第一个数据,并删除之 
	}
}

猜你喜欢

转载自blog.csdn.net/Authur520/article/details/84886802
今日推荐