题解 | #把二叉树打印成多行#
把二叉树打印成多行
http://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288
之前做过一道一模一样但是名字不同的题。这次就当是复习了。思路就不再写了,可以点这里看。
/*
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<vector<int>> result;
if(!pRoot){
return result;
}
go(pRoot, 0, result);
return result;
}
void go(TreeNode* p, int level, vector<vector<int>> &result){
if(level == result.size()){
vector<int> blank;
result.push_back(blank);
}
result.at(level).push_back(p->val);
if(p->left){
go(p->left, level + 1, result);
}
if(p->right){
go(p->right, level + 1, result);
}
}
};