用队列实现二叉树层序遍历

用队列实现二叉树层序遍历_第1张图片

就是说一层一层遍历

创建一个队列来储存数据

画图理解一下:
用队列实现二叉树层序遍历_第2张图片

 完整代码:
 

//层序遍历
typedef struct QueueNode
{
	int data;
	struct Queue* next;
}QueueNode;
typedef struct Queue
{
	QueueNode* head;
	QueueNode* tail;
}Queue;


typedef struct BinaryTreeNode
{
	int data;
	struct BinaryTreeNode* left;
	struct BinaryTreeNode* right;
}BTNode;

//创建结点
BTNode* BuyNode(BTNode* x)
{
	BTNode* node = (BTNode*)malloc(sizeof(BTNode));
	node->data = x;
	node->left = NULL;
	node->right = NULL;
	return node;
}
BTNode* CreatBinaryTree()
{
	BTNode* node1 = BuyNode(1);
	BTNode* node2 = BuyNode(2);
	BTNode* node3 = BuyNode(3);
	BTNode* node4 = BuyNode(4);
	BTNode* node5 = BuyNode(5);
	BTNode* node6 = BuyNode(6);
	//BTNode* node7 = BuyNode(7);

	node1->left = node2;
	node1->right = node4;
	node2->left = node3;
	node4->left = node5;
	node4->right = node6;
	//node5->left = node7;


	return node1;
}

void QueueInit(Queue* pq)
{
	pq->head = NULL;
	pq->tail = NULL;
}


void Push(Queue* pq,BTNode*root)
{
	QueueNode* newnode = (QueueNode*)malloc(sizeof(QueueNode));
	newnode->data = root;
	newnode->next = NULL;
	if (pq->head == NULL)
	{
		pq->head = pq->tail = newnode;
	}
	else
	{
		pq->tail->next = newnode;
		pq->tail = newnode;
	}
}

//销毁队列
void DestoryQueue(Queue* pq)
{
	QueueNode* cur = pq->head;
	while (cur)
	{
		QueueNode* next = cur->next;
		free(cur);
		cur = next;
	}
	pq->head = pq->tail = NULL;
}

//删除队头
void PopFront(Queue* pq)
{
	QueueNode* newhead = pq->head->next;
	free(pq->head);
	pq->head = newhead;
	if (pq->head == NULL)
	{
		pq->tail = NULL;
	}
}

//输出队头
int QueueFront(Queue* pq)
{
	return pq->head->data;
}

//判断是否为空
bool QueueEmpty(Queue* pq)
{
	return pq->head == NULL;
}

int main()
{
	Queue pq;
	QueueInit(&pq);


	BTNode* root = CreatBinaryTree();
	if (root)
	{
		Push(&pq, root);
	}
	while (!QueueEmpty(&pq))
	{
		BTNode* front = QueueFront(&pq);
		printf("%d ", front->data);
		PopFront(&pq);

		if (front->left)
		{
			Push(&pq, front->left);
		}

		if (front->right)
		{
			Push(&pq, front->right);
		}
	}
}

 如有错误,多多指教!

你可能感兴趣的:(数据结构,leetcode,leetcode)