菜鸟笔记
提升您的技术认知

打印二叉树的方法

层序遍历

之前学到层序遍历的方法,分组打印每一层,但是效果似乎不是很好。因为还需要自己判断

//层序遍历分组输出
vector<vector<char> >levelGroup(TreeNode* root)
{
  
	queue<TreeNode*>que;
	que.push(root);
	vector<vector<char> >ans;
	while(!que.empty())
	{
  
		vector<char> temp;
		int len=que.size();
		for(int i=0;i<len;i++)
		{
  
			TreeNode* node=que.front();
			temp.push_back(node->val);
			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<TreeNode *> q;
    q.push(root);
    while (!q.empty()){
  
        vector<TreeNode*> cache;
        //取出队列中位于同一行的结点 放到cache中 
        while (!q.empty()){
   cache.push_back(q.front()); q.pop(); }
        string line = "                           ";
        for (int i=0;i<cache.size();i++)
        {
  
        	TreeNode* p=cache[i];
        	//遍历同一行的结点 按照它们在中序序列的位置 修改在line中的位置 
        	if (p)
			{
  
            line[midT.find(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;
    }

}