如何将二叉树以多行形式进行打印输出?
- 内容介绍
- 文章标签
- 相关推荐
本文共计269个文字,预计阅读时间需要2分钟。
题目描述:打印从上到下按层打印二叉树,同一层节点从左至右输出。每一层输出一行。
链接:[牛客网 - 二叉树的层序遍历](https://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288?tpId=13tqId=11213rp=2ru=/ta/coding-interviewsru=/ta/codings)
题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
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;
}
};
本文共计269个文字,预计阅读时间需要2分钟。
题目描述:打印从上到下按层打印二叉树,同一层节点从左至右输出。每一层输出一行。
链接:[牛客网 - 二叉树的层序遍历](https://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288?tpId=13tqId=11213rp=2ru=/ta/coding-interviewsru=/ta/codings)
题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
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;
}
};

