之前学到层序遍历的方法,分组打印每一层,但是效果似乎不是很好。因为还需要自己判断
//层序遍历分组输出
vector >levelgroup(treenode* root)
{
queueque;
que.push(root);
vector >ans;
while(!que.empty())
{
vector temp;
int len=que.size();
for(int i=0;ival);
que.pop();
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
ans.push_back(temp);
}
return ans;
}
结果:
接下来的内容转载自https://blog.csdn.net/u010909667/article/details/54972495
这种打印方法实在巧妙 每次用新的string来存当前层的结点,然后在队列中把当前结点的值按照中序遍历的结果保存下来,然后再打印
//2 打印树的结构
void treeprint(treenode* root)
{
queue q;
q.push(root);
while (!q.empty()){
vector cache;
//取出队列中位于同一行的结点 放到cache中
while (!q.empty()){
cache.push_back(q.front()); q.pop(); }
string line = " ";
for (int i=0;ifind(p->val)] = p->val;
//将结点的左右孩子入队
if (p->left) q.push(p->left);
if (p->right) q.push(p->right);
}
}
//输出之前修改的line
cout << line << endl;
}
}
结果
效果如下图 代码
void show(treenode *parent,treenode* root,string &prefix){
prefix = "|";
if (root){
cout << prefix<<"--" << root->val << endl;
if (root==parent||root == parent->right){
prefix.erase(prefix.end()-1); prefix = " ";
}
prefix = " ";
show(root,root->left, prefix);
show(root,root->right, prefix);
}else{
if (parent->left || parent->right)
cout << prefix << "--" << "{}"<< endl;
}
}