题目描述 从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。 https://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288?tpId=13tqId=11213rp=2ru=/ta/coding-interviewsqru=/ta/codi
题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
https://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288?tpId=13&tqId=11213&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
题解:
class Solution {public:
vector<vector<int> > Print(TreeNode* pRoot) {
queue<TreeNode*> q;
int cnt = 1;
if (pRoot == NULL) {
return {};
}
q.push(pRoot);
vector<vector<int>> res;
vector<int> tmp;
while (q.empty() == false) {
TreeNode *t = q.front();
q.pop();
tmp.push_back(t->val);
cnt--;
if (t->left != NULL) {
q.push(t->left);
}
if (t->right != NULL) {
q.push(t->right);
}
if (cnt == 0) {
cnt = q.size();
res.push_back(tmp);
tmp.clear();
}
}
return res;
}
};