fork(1) download
  1. #include <map>
  2. #include <vector>
  3. #include <iostream>
  4.  
  5. using namespace std;
  6.  
  7. struct TreeNode {
  8. int val;
  9. TreeNode *left;
  10. TreeNode *right;
  11. TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  12. };
  13.  
  14. class Solution {
  15. public:
  16. map<int, vector<int> > levelValues;
  17. void recursivePrint(TreeNode *root, int depth){
  18. if(root == NULL)
  19. return;
  20. if(levelValues.count(root->val) == 0)
  21. levelValues.insert(make_pair(depth, vector<int>()));
  22. levelValues[depth].push_back(root->val);
  23. recursivePrint(root->left, depth+1);
  24. recursivePrint(root->right, depth+1);
  25.  
  26. }
  27.  
  28. vector<vector<int> > levelOrder(TreeNode *root) {
  29. recursivePrint(root, 1);
  30. vector<vector<int> > result;
  31. for(map<int,vector<int> >::iterator it = levelValues.begin(); it!= levelValues.end(); ++it){
  32. result.push_back(it->second);
  33. }
  34. return result;
  35. }
  36. };
  37.  
  38.  
  39. int main(){
  40. TreeNode node(1);
  41. Solution S;
  42. vector<vector<int> > double_vec;
  43. double_vec = S.levelOrder(&node);
  44. int i=0,j=0;
  45. for(i=0;i<double_vec.size();i++){
  46. for(j=0;j<double_vec[i].size();j++)
  47. cout << double_vec[i][j] << " ";
  48. cout << endl;
  49. }
  50.  
  51. return 1;
  52. }
Runtime error #stdin #stdout 0s 2868KB
stdin
Standard input is empty
stdout
1