把二叉树打印成多行

/*

从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。

*/

class Solution
{
public:
vector<vector<int> > Print(TreeNode* pRoot)
{

vector<vector<int> > v_result;
vector<int> v_temp;
queue<pair<TreeNode*, int>> q;
if(!pRoot)
{
return v_result;
}
q.push(make_pair(pRoot, 0));
int preHeight = 0;
while(!q.empty())
{
pair<TreeNode*, int> pa_Node = q.front();
q.pop();
TreeNode* pTemp = pa_Node.first;
int height = pa_Node.second;
if(height == preHeight)
{
v_temp.push_back(pTemp->val);
}
else
{
v_result.push_back(v_temp);
v_temp.clear();
v_temp.push_back(pTemp->val);
preHeight = height;
}
if(pTemp->left)
{
q.push(make_pair(pTemp->left, height+1));
}
if(pTemp->right)
{
q.push(make_pair(pTemp->right, height+1));
}
}
if (!v_temp.empty())
{
v_result.push_back(v_temp);
}
return v_result;
}

};

原文地址:https://www.cnblogs.com/mengjuanjuan/p/10561569.html