从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
// 1.按照层打印二叉树,需要使用队列,先进先出
// 2.每层打印一行,需要判断当前行有多少个节点,然后打印换行
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
//首先将二叉树存入到队列中
vector<vector<int>> t;
queue<TreeNode*> que;
if(pRoot==NULL) return t;
que.push(pRoot);
int next = 0;
int current = 1;
while(!que.empty()) {
vector<int> node;
while(current != 0 && !que.empty()){ //对当前层进行存储,并统计下一层的个数
TreeNode* top = que.front();
node.push_back(top->val);
current--;
que.pop();
if(top->left!=NULL) {
que.push(top->left);
next++;
}
if(top->right!=NULL) {
que.push(top->right);
next++;
}
}
t.push_back(node);
current = next;
next = 0;
}
return t;
}
};

本文介绍了一种二叉树的层次遍历算法,通过队列实现从上到下、从左至右的节点输出。文章详细解释了如何使用队列来跟踪每一层的节点,确保同一层的节点在同一行输出。
1345

被折叠的 条评论
为什么被折叠?



