面试题02 从上往下打印二叉树 【树】[ water ]

题目:输入一颗二元树,从上往下按层打印树的每个结点,同一层中按照从左往右的顺序打印。

例如输入

   8
          / \
        6  10
        /\    /\
      5 7 9 11

输出8 6 10 5 7 9 11。
解法:树是图的一种特殊的退化形式。本题就是一个广度优先遍历图的问题

#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <vector>
#include <stack>
#include <deque>
#include <queue>
#include <bitset>
#include <list>
#include <map>
#include <set>
#include <iterator>
#include <algorithm>
#include <functional>
#include <utility>
#include <sstream>
#include <climits>
#include <cassert>
#define BUG puts("here!!!");

using namespace std;
struct Node {
	int value;
	Node* lchild;
	Node* rchild;
};
queue<Node*> Q;
void bfs(Node* pn) {
	if(pn == NULL) return;
	Q.push(pn);	
	while(!Q.empty()) {
		Node* t = Q.front();
		printf("%d ", t->value);
		if(t->lchild) {
			Q.push(t->lchild);
		}
		if(t->rchild) {
			Q.push(t->rchild);
		}
	}
}	
int main() {
	return 0;
}

原文地址:https://www.cnblogs.com/robbychan/p/3787174.html