题目:有一棵二叉树,请设计一个算法,按照层次打印这棵二叉树,分层输出。
题目有两个难点,一个是二叉树的分层遍历,一个是换行输出。分层遍历时需要注意使用队列来存储访问过的节点的子节点,换行输出主要是考虑使用标志位来确定是否访问到了某一层的末尾。
《编程之美》上给出的解法:
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
class TreePrinter {
public:
void printTree(TreeNode* root) {
if(root = NULL)
return;
vector<TreeNode*> vec;
vec.push_back(root);
int cur = 0;
int last = 1;
while(cur<vec.size())
{
last = vec.size();
while(cur<last)
{
cout<<vec[cur]->val<<" ";
if(!vec[cur]->left)
vec.push_back(vec[cur]->left);
if(!vec[cur]->right)
vec.push_back(vec[cur]->right);
cur++;
}
cout<<endl;
}
}
};
牛客网上关于这道题目的要求是:
有一棵二叉树,请设计一个算法,按照层次打印这棵二叉树。
给定二叉树的根结点root,请返回打印结果,结果按照每一层一个数组进行储存,所有数组的顺序按照层数从上往下,且每一层的数组内元素按照从左往右排列。保证结点数小于等于500。
解法如下:
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
class TreePrinter {
public:
vector<vector<int> > printTree(TreeNode* root) {
int dep[550],head = 0,tail = 0;
TreeNode *now,*q[550];
q[tail ++] = root; dep[root->val] = 0;
while(head != tail){
now = q[head ++];
if(now->left) q[tail ++] = now->left,dep[now->left->val] = dep[now->val] + 1;
if(now->right) q[tail ++] = now->right,dep[now->right->val] = dep[now->val] + 1;
}
vector<vector<int> > ret;
for(int j,i = 0;i < tail;i = j){
vector<int> tmp;
j = i;
while(j < tail && dep[q[j]->val] == dep[q[i]->val]){
tmp.push_back(q[j]->val);
++ j;
}
ret.push_back(tmp);
}
return ret;
}
};