Advertisement
VaishanviShri

Untitled

Jul 1st, 2022
903
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.10 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     TreeNode *left;
  6.  *     TreeNode *right;
  7.  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8.  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9.  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10.  * };
  11.  */
  12. class Solution {
  13. public:
  14.     void insert(TreeNode* node, int level,unordered_map<int, vector<int>>& order){
  15.         if(node==nullptr)
  16.             return;
  17.         if(order.find(level)==order.end())
  18.             order[level] ={node->val};
  19.         else
  20.             order[level].push_back(node->val);
  21.        
  22.         insert(node->left, level+1, order);
  23.         insert(node->right, level+1, order);
  24.     }
  25.     vector<vector<int>> levelOrder(TreeNode* root) {
  26.         if(root==nullptr)
  27.             return {};
  28.         unordered_map<int, vector<int>> order;
  29.         insert(root, 0, order);
  30.         vector<vector<int>> ans;
  31.         for(int i = 0;i<order.size();i++){
  32.             ans.push_back(order[i]);
  33.         }
  34.         return ans;
  35.     }
  36. };
  37.  
  38.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement