马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 糖逗 于 2020-5-8 18:11 编辑
题目描述:从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
提示:
节点总数 <= 1000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-ii-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
#include <iostream>
#include <vector>
#include <queue>
#include <malloc.h>
using namespace std;
struct TreeNode{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x): val(x), left(NULL), right(NULL){
}
};
TreeNode* CreateTree(vector<int>& input){
TreeNode* tree = (TreeNode*)malloc(sizeof(TreeNode)*input.size());
for(int i = 0; i < input.size() ;i++){
tree[i].val = input[i];
tree[i].left = NULL;
tree[i].right = NULL;
}
for(int i = 0; i <= input.size()/2-1; i++){
if(2*i+1 <= input.size()){
tree[i].left = &tree[2*i+1];
}
if(2*i+2<=input.size()){
tree[i].right = &tree[2*i+2];
}
}
return tree;
}
vector<vector<int> > solution(TreeNode* root){
vector<vector<int> > res;
if(root == NULL) return res;
queue<TreeNode*> temp;
temp.push(root);
while(!temp.empty()){
vector<int> temp1;
int length = temp.size();
for(int i = 0; i < length; i++){
TreeNode* node = temp.front();
temp1.push_back(node -> val);
temp.pop();
if(node -> left) temp.push(node -> left);
if(node -> right) temp.push(node -> right);
}
res.push_back(temp1);
}
return res;
}
int main(void){
vector<int>input;
int number;
cout << "please send numbers for this tree:" << endl;
while(cin >> number){
input.push_back(number);
}
TreeNode* root = CreateTree(input);
vector<vector<int> > res = solution(root);
for(int i = 0; i < res.size(); i++){
for(int j = 0; j < res[i].size();j++){
if(res[i][j] == 0){
cout << " ";
}
else{
cout << res[i][j];
}
}
cout << endl;
}
return 0;
}
注意事项:
1.一层层打印。
2.细节有很多坑。
|