把二叉樹列印成多行 c++
題目描述
從上到下按層列印二叉樹,同一層結點從左至右輸出。每一層輸出一行。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<int> item;
vector<vector<int> > result;
if(pRoot==NULL) return result;
queue<pair<TreeNode*,int> > Q;
Q.push(make_pair(pRoot,1));
int old_deep=0;
while(!Q.empty())
{
TreeNode* node=Q.front().first;
int deep=Q.front().second;
Q.pop();
if(item.size()==0)
{
item.push_back(node->val);
old_deep=deep;
}else
{
if(old_deep!=deep)
{
result.push_back(item);
item.clear();
item.push_back(node->val);
old_deep=deep;
}else
{
item.push_back(node->val);
}
}
if(node->left)
{
Q.push(make_pair(node->left,deep+1));
}
if(node->right)
{
Q.push(make_pair(node->right,deep+1));
}
}
if(item.size()!=0)
{
result.push_back(item);
}
return result;
}
};