从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行,数据之间用一个空格分隔,行尾无多余空格。
二叉树结点类型定义:
struct TreeNode {
int val; struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
函数接口定义:
vector<vector<int> > Print(TreeNode* pRoot);
其中 pRoot
为指向二叉树的根结点的指针。函数须返回二叉树层次遍历结果。
裁判测试程序样例:
#include <bits/stdc++.h>using namespace std;struct TreeNode {
int val; struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};class Solution {public: /* 请在这里填写答案 */};
输入样例:
样例二叉树:
输出样例:
7
2 6
9 4 8 5
10 3
作者李廷元单位民用航空飞行学院代码长度限制16 KB时间限制400 ms内存限制64 MBvector<vector<int>>Print(TreeNode* pRoot){
vector<vector<int>>res;
queue<TreeNode*>tmp;
TreeNode* ptr=nullptr;
if(pRoot==nullptr)
return res;
tmp.push(pRoot);
while(!tmp.empty()){
vector<int>tmp1;
int i=0,len=tmp.size();
while(i++<len){
ptr=tmp.front();
tmp.pop();
tmp1.push_back(ptr->val);
if(ptr->left!=nullptr)
tmp.push(ptr->left);
if(ptr->right!=nullptr)
tmp.push(ptr->right);
}
res.push_back(tmp1);
}
return res;
}
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行,数据之间用一个空格分隔,行尾无多余空格。
二叉树结点类型定义:
struct TreeNode {
int val; struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
函数接口定义:
vector<vector<int> > Print(TreeNode* pRoot);
其中 pRoot
为指向二叉树的根结点的指针。函数须返回二叉树层次遍历结果。
裁判测试程序样例:
#include <bits/stdc++.h>using namespace std;struct TreeNode {
int val; struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};class Solution {public: /* 请在这里填写答案 */};
输入样例:
样例二叉树:
输出样例:
7
2 6
9 4 8 5
10 3
作者
李廷元
单位
民用航空飞行学院
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
vector<vector<int>>Print(TreeNode* pRoot){ vector<vector<int>>res; queue<TreeNode*>tmp; TreeNode* ptr=nullptr; if(pRoot==nullptr) return res; tmp.push(pRoot); while(!tmp.empty()){ vector<int>tmp1; int i=0,len=tmp.size(); while(i++<len){ ptr=tmp.front(); tmp.pop(); tmp1.push_back(ptr->val); if(ptr->left!=nullptr) tmp.push(ptr->left); if(ptr->right!=nullptr) tmp.push(ptr->right); } res.push_back(tmp1); } return res; }