微软面试题2

21 篇文章 0 订阅

微软、谷歌、百度等公司经典面试100题[第1-60题] 

怎样从顶部开始逐层打印二叉树结点数据?请编程。

#include<iostream>
#include<queue>
#include<time.h>
using namespace std;
struct node
{
	int value;
	node* left;
	node* right;
	node(int v)
	{
		value = v;
		left = NULL;
		right = NULL;
	}
};
class bintree
{
private:
	node* root;
public:
	bintree()
	{
		root = NULL;
	}
	void insert(int value)
	{
		if(root == NULL)
			root = new node(value);
		else
		{
			node* tmp = root;
			node* parent = root;
			int flag = 0;
			while(tmp != NULL)
			{
				parent = tmp;
				srand(time(NULL));
				flag = rand() % 2;
				if(flag == 1)//奇数往左边走,偶数往右边走
					tmp = tmp->left;
				else tmp = tmp->right;
			}
			node* child = new node(value);
			if(flag == 1)
				parent->left = child;
			else parent->right = child;
		}
	}
	void print()//逐层打印节点数据
	{
		if(root == NULL)
			return;
		queue<node*> q;
		node* tmp = root;
		q.push(tmp);
		int count = 0;
		int m = 0;
		while(!q.empty())//用队列存储节点
		{
			cout << (q.front())->value << ' ';
			node* parent = q.front();
			if(parent->left != NULL)
				q.push(parent->left);
			if(parent->right != NULL)
				q.push(parent->right);
			q.pop();
		}
	}
};

int main()
{
	int i;
	bintree tree;
	while(true)
	{
		cin >> i;
		if(i == -1)
			break;
		tree.insert(i);
	}
	tree.print();

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值