题目(微软):
输入一颗二元树,从上往下按层打印树的每个结点,同一层中按照从左往右的顺序打印。
例如输入
8
/ \
6 10
/ \ / \
5 7 9 11
输出8 6 10 5 7 9 11。
-----------------------------------
仍然是二叉树,那就是遍历问题了,好了,这里遍历似乎不是我们以往的遍历方式,如果按照那些先序 中序 后序发现是以深度优先的遍历方式,而这里更希望的是以宽度打印,当然这里就需要借助一个存储机制,当然又是链表,在想想,链表先加入 的元素应该是层数较上的,应该被打印出,然后在把它的下层加入,以此类推
终于,这道题又写了一个好久没有写的数据结构---队列!!
好了,看到这里大家应该可以得到答案了。
下面给出本题答案,同时还是练习了下中序打印,虽然确实很简单。。。
希望大家能自己写个队列,练习算法的时候还是尽量少用库里的Queue
//============================================================================
// Name : PrintBT.cpp
// Author : YLF
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
using namespace std;
/*
* 二叉树的节点
*/
struct Node{
int value;
Node* left;
Node* right;
};
/*
* 队列节点
*/
struct QueueNode{
Node* node;
QueueNode* next;
};
void addNode(Node* &p, int value);
void printBT(Node* p);
void printBTByFloor();
QueueNode* containerHead = NULL;
QueueNode* containerCur = NULL;
int main() {
Node* head = NULL;
int input = 0;
while(true){
cin>>input;
if(input != -1)
addNode(head, input);
else
break;
}
printBT(head);
cout<<endl;
//同层打印
if(head){
containerHead = new QueueNode();
containerHead->next = NULL;
containerHead->node = head;
containerCur = containerHead;
}
printBTByFloor();
return 0;
}
void addNode(Node* &p, int value){
if(p == NULL){
Node* temp = new Node();
temp->value = value;
temp->left = NULL;
temp->right = NULL;
p = temp;
}else{
if(value < p->value)
addNode(p->left, value);
else
addNode(p->right, value);
}
}
/*
* 按照每层顺序打印
*/
void printBTByFloor(){
if(containerHead == NULL)
return;
cout<<containerHead->node->value<<" ";
if(containerHead->node->left){
QueueNode* l = new QueueNode();
l->node = containerHead->node->left;
l->next = NULL;
containerCur->next = l;
containerCur = l;
}
if(containerHead->node->right){
QueueNode* r = new QueueNode();
r->node = containerHead->node->right;
r->next = NULL;
containerCur->next = r;
containerCur = r;
}
QueueNode* temp = containerHead;
containerHead = containerHead->next;
delete temp;
printBTByFloor();
}
/*
* 中序打印
*/
void printBT(Node* p){
if(p == NULL)
return;
printBT(p->left);
cout<<p->value<<" ";
printBT(p->right);
}