#include <iostream>
#include <vector>
#include <queue>
#include <cassert>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
if(root == NULL)
return res;
queue<pair<TreeNode*,int>> q;
q.push(make_pair(root, 0));
while(!q.empty()){
TreeNode* node = q.front().first;
int level = q.front().second;
q.pop();
if(level == res.size())
res.push_back(vector<int>());
assert( level < res.size() );
res[level].push_back(node->val);
if(node->left)
q.push(make_pair(node->left, level + 1 ));
if(node->right)
q.push(make_pair(node->right, level + 1 ));
}
return res;
}
};
void deallocate_tree(TreeNode* t){
if(t != NULL){
deallocate_tree(t->left);
deallocate_tree(t->right);
delete t;
}
}
TreeNode* cons_tree(int e, TreeNode* l, TreeNode* r){
TreeNode* tmp;
tmp = new TreeNode(e);
tmp->left = l;
tmp->right = r;
return tmp;
}
TreeNode* ordered_insertion_tree(int e, TreeNode* t){
// BST
if (t == NULL) {
return cons_tree(e, NULL, NULL);
} else if (e < t->val) {
t->left = ordered_insertion_tree(e, t->left);
return t;
} else {
t->right = ordered_insertion_tree(e, t->right);
return t;
}
}
int main() {
TreeNode* t = NULL;
t = ordered_insertion_tree(15, t);
t = ordered_insertion_tree(20, t);
t = ordered_insertion_tree(6, t);
t = ordered_insertion_tree(1, t);
t = ordered_insertion_tree(4, t);
t = ordered_insertion_tree(18, t);
t = ordered_insertion_tree(9, t);
t = ordered_insertion_tree(50, t);
vector<vector<int>> v = Solution().levelOrder(t);
cout<< v.size() <<endl;
for (int i = 0; i < v.size(); i++) {
for (int j = 0; j < v[i].size(); j++) {
cout<< v[i][j] <<" ";
}
cout <<endl;
}
cout <<endl;
deallocate_tree(t);
return 0;
}
08-21
1091
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)