/*
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 == nullptr) return result;
queue<TreeNode*> tool;
tool.push(pRoot);
int currentLineNum = 0;
int nextLineNum = 1;
// vector<int> currentLine;
while(!tool.empty()) {
currentLineNum = nextLineNum;
nextLineNum = 0;
// currentLine.clear();
vector<int> currentLine;
TreeNode* pNode;
for(int i=0; i<currentLineNum; i++) {
pNode = tool.front();
tool.pop();
currentLine.push_back(pNode->val);
if(pNode->left != nullptr) {
tool.push(pNode->left);
nextLineNum++;
}
if(pNode->right != nullptr) {
tool.push(pNode->right);
nextLineNum++;
}
}
result.push_back(currentLine);
}
return result;
}
};
用了队列。
小错误:result类型定义错;最后忘反result。
其中我在每次往result里推入一个 新vector<int>类型的元素的时候犹豫了是每次都新声明一个还是只定义一个,每次调用.clear()【注释位置】,因为不知道vector变量名是不是类似于数组的地址,如果只用一个的话最后result的所有元素都是最后的那个vector<int>.答案正确后试了试貌似两种写法都可以 : )
本来觉得自己还行,一进讨论区就会有大神:
/*
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;
handleByDepth(pRoot, 1, result);
return result;
}
void handleByDepth(TreeNode* pNode,
int depth,
vector<vector<int>>& result) {
if (pNode == nullptr) return;
if(result.size() < depth) {
vector<int> temp;
result.push_back(temp); // vector好像不能new啊
}
result[depth-1].push_back(pNode->val);
handleByDepth(pNode->left, depth+1, result);
handleByDepth(pNode->right, depth+1, result);
}
};
第一次提交这个方法,有注释的那里是这样写的
result.push_back(new vector<int>());
结果报错,因为push_back的内容不匹配。看来vector可能不能用new声明?
总结:
多动脑子,好的(简洁的)算法都是一部分工作已经用人脑操作了,不然就得依赖电脑的优势(快,奉命行事)来补足了。
二刷:简洁了一些
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int> > result;
if(pRoot == nullptr) return result;
int thisLevel = 1;
int nextLevel = 0;
queue<TreeNode*> q;
q.push(pRoot);
TreeNode* pNode;
vector<int> level;
while(!q.empty()) {
pNode = q.front();
q.pop();
level.push_back(pNode->val);
if(pNode->left != nullptr) {
q.push(pNode->left);
nextLevel++;
}
if(pNode->right != nullptr) {
q.push(pNode->right);
nextLevel++;
}
thisLevel--;
if(thisLevel == 0) {
result.push_back(level);
level.clear();
thisLevel = nextLevel;
nextLevel = 0;
}
}
return result;
}
};