题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
解题思路
二叉树的层次序遍历即可,注意vector的边界条件
AC代码
class Solution {
public:
vector<vector<int>> Print (TreeNode* pRoot) {
vector<vector<int>> res;
if (pRoot == nullptr) {
return res;
}
queue<Node> que;
que.emplace (Node (pRoot, 0));
while (!que.empty()) {
auto t = que.front();
que.pop();
if (res.size() < t.depth + 1) { // 注意深度判别
vector<int>vec;
res.emplace_back (vec);
}
res[t.depth].push_back (t.ptr->val);
if (t.ptr->left != nullptr) {
que.emplace (Node (t.ptr->left, t.depth + 1));
}
if (t.ptr->right != nullptr) {
que.emplace (Node (t.ptr->right, t.depth + 1));
}
}
return res;
}
struct Node {
TreeNode* ptr;
int depth;
Node (TreeNode* p, int dp):
ptr (p), depth (dp) {}
};
};