Bloomberg 面试题05012012[2]

本文介绍如何使用C++实现二叉树的层次遍历,从根节点开始,逐层打印每个节点的值。

You have a binary tree. Print node values starting from the root going level by level, i.e. first line has root node's value, second line has two child node's values, third line - left and right child nodes values of the root's left child then left and right child nodes values of the root's right child, and so on.


#include <iostream>
#include <queue>

struct node
{
	int data;
	node* left;
	node* right;
	node(int _data, node* _left, node* _right)
	{
		data = _data;
		left = _left;
		right = _right;
	}
};



int main()
{
	node* n7 = new node(7, NULL, NULL);
	node* n6 = new node(6, NULL, NULL);
	node* n5 = new node(5, NULL, NULL);
	node* n4 = new node(4, NULL, NULL);
	node* n3 = new node(3, n6, n7);
	node* n2 = new node(2, n4, n5);
	node* n1 = new node(1, n2, n3);
	node* root = n1;

	std::queue<node*> q;
	q.push(root);
	q.push(NULL);

	while(!q.empty())
	{
		node* cur = q.front();
		if(cur != NULL)
		{
			printf("%d ", cur->data);
			q.pop();
			if(cur->left != NULL)
				q.push(cur->left);
			if(cur->right != NULL)
				q.push(cur->right);
		}
		else
		{
			if(q.size() == 1)
				break;
			else
			{
				q.pop();
				q.push(NULL);
				printf("\n");
			}
		}
	}

	return 0;

}


评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值