# 按层次遍历二叉树

199人阅读 评论(0)

《编程之美》上给出的解法:

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;

}

}
};

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;
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;
}
};
1
0

个人资料
• 访问：111544次
• 积分：3378
• 等级：
• 排名：第11802名
• 原创：223篇
• 转载：15篇
• 译文：2篇
• 评论：19条
最新评论