从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
提示:
节点总数 <= 1000
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
};
int n=-1;
TreeNode* create(vector<int> tree){
++n;
TreeNode *root;
if(n>=tree.size()){
return NULL;
}
else{
if(tree[n]==0){
root = nullptr;
}
else{
root = new TreeNode;
root->val = tree[n];
root->left = create(tree);
root->right = create(tree);
}
}
return root;
}
vector<vector<int> > BFS(TreeNode *root){
vector<vector<int> > v;
if(root == nullptr) return v;
deque<TreeNode*> d;
d.push_back(root);
bool leftorright=true;
while(!d.empty()){
int size = d.size();
vector<int> m;
for(int i=0; i<size; i++){
if(leftorright){
TreeNode* node = d.front();
m.push_back(node->val);
d.pop_front();
if(node->left != nullptr) d.push_back(node->left);
if(node->right != nullptr) d.push_back(node->right);
}
else{
TreeNode* node = d.back();
m.push_back(node->val);
d.pop_back();
if(node->right != nullptr) d.push_front(node->right);
if(node->left != nullptr) d.push_front(node->left);
}
}
v.push_back(m);
leftorright = !leftorright;
}
return v;
}
int main(){
vector<int> tree;
tree.push_back(3);
tree.push_back(9);
tree.push_back(0);
tree.push_back(0);
tree.push_back(20);
tree.push_back(15);
tree.push_back(7);
TreeNode *root = create(tree);
vector<vector<int> > v = BFS(root);
for(int i=0; i<v.size(); i++){
for(int j=0; j<v[i].size(); j++){
printf("%d ", v[i][j]);
}
}
return 0;
}