#include <stdio.h>
#include <string.h>
#include <iostream>
#include <vector>
#include <queue>
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {
}
};
static constexpr int TERMINATION = -1;
struct TreeNode *root = nullptr;
void create_root(struct TreeNode *&ptr) {
int x;
std::cin >> x;
if (TERMINATION == x) {
return;
}
if (nullptr == ptr) {
ptr = new TreeNode(x);
create_root(ptr->left);
create_root(ptr->right);
}
}
std::vector<std::vector<int>> levelOrder(TreeNode* root) {
if (nullptr == root) {
return std::vector<std::vector<int>>();
}
std::queue<TreeNode *>tree_node_ptr_queue;
std::vector<int>lay_nodes_vec;
std::vector<std::vector<int>>lays_nodes_vec;
tree_node_ptr_queue.push(root);
int lay_nodes = 1;
int next_lay_nodes = 0;
while (false == tree_node_ptr_queue.empty()) {
auto ptr = tree_node_ptr_queue.front();
lay_nodes_vec.emplace_back(ptr->val);
tree_node_ptr_queue.pop();
lay_nodes--;
if (ptr->left != nullptr) {
tree_node_ptr_queue.push(ptr->left);
++next_lay_nodes;
}
if (ptr->right != nullptr) {
tree_node_ptr_queue.push(ptr->right);
++next_lay_nodes;
}
if (0 == lay_nodes) {
lays_nodes_vec.emplace_back(lay_nodes_vec);
lay_nodes_vec.clear();
lay_nodes = next_lay_nodes;
next_lay_nodes = 0;
}
}
return lays_nodes_vec;
}
int main() {
create_root(root);
std::vector<std::vector<int>> vec = levelOrder(root);
for (auto &e : vec) {
std::cout << "lay size = " << e.size() << std::endl;
for (auto &x : e) {
std::cout << x << " ";
}
std::cout << std::endl;
}
return 0;
}
/**标签:node,std,遍历,leetcode,vec,二叉树,nodes,ptr,lay From: https://blog.51cto.com/u_15899033/5902960
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
if (nullptr == root) {
return std::vector<std::vector<int>>();
}
std::queue<TreeNode *>tree_node_ptr_queue;
std::vector<int>lay_nodes_vec;
std::vector<std::vector<int>>lays_nodes_vec;
tree_node_ptr_queue.push(root);
int lay_nodes = 1;
int next_lay_nodes = 0;
while (false == tree_node_ptr_queue.empty()) {
auto ptr = tree_node_ptr_queue.front();
lay_nodes_vec.emplace_back(ptr->val);
tree_node_ptr_queue.pop();
lay_nodes--;
if (ptr->left != nullptr) {
tree_node_ptr_queue.push(ptr->left);
++next_lay_nodes;
}
if (ptr->right != nullptr) {
tree_node_ptr_queue.push(ptr->right);
++next_lay_nodes;
}
if (0 == lay_nodes) {
lays_nodes_vec.emplace_back(lay_nodes_vec);
lay_nodes_vec.clear();
lay_nodes = next_lay_nodes;
next_lay_nodes = 0;
}
}
return lays_nodes_vec;
}
};