题目:
思路:
先获取树的高度(层次),再通过递归按层次输出
代码:
#include <iostream>
using namespace std;
class Node { //树节点
public:
char data;
Node *Left;
Node *Right;
Node() : data('0'), Left(NULL),Right(NULL) {}
};
class Tree {
public:
Node *root;
Tree() {
root = new Node();
}
void create(Node* &p){ //根据题目给的先序遍历结果建树
char c;
cin>>c;
if(c!='0'){
p = new Node;
p->data=c;
create(p->Left);
create(p->Right);
}
else{
p = NULL;
}
}
int height(Node *p){ //递归函数获取树的高度
if(!p) return 0; //没有返回0
else{
int h_left = height(p->Left); //左高度
int h_right = height(p->Right); //右高度
if(h_left>h_right){ //二者选最高的返回
return h_left+1;
}
else return h_right+1;
}
return 0;
}
void operate(Node *p){
if(!p) return;
int h = height(root); //得到树高度
for(int i =1;i<=h;i++){
print(p,i); //对每一层进行打印
}
}
void print(Node *p, int k){ //打印函数
if(!p) return;
if(k == 1)
cout<<p->data; //为1再输出数据
else{
print(p->Left,k-1); //往左直到k为1
print(p->Right,k-1); //往右...
}
}
};
int main(){
int t;
cin>>t;
while(t--){
Tree tree;
tree.create(tree.root);
tree.operate(tree.root);
cout<<endl;
}
return 0;
}
其他:
为什么其他人不用算高度也能层次遍历呢?赶紧去学学()
才发现原来题目要求用队列实现,呃呃呃(> _ <)
那就假装没看到罢
欸嘿( •ω• )