farkhatmikhalko

n-ary-tree-preorder-traversal

Oct 26th, 2019
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.75 KB | None | 0 0
  1. /*
  2. Runtime: 144 ms, faster than 90.97% of C++ online submissions for N-ary Tree Preorder Traversal.
  3. Memory Usage: 33.2 MB, less than 21.05% of C++ online submissions for N-ary Tree Preorder Traversal.
  4. */
  5.  
  6. class Solution {
  7. public:
  8.     vector<int> preorder(Node* root) {
  9.         stack<Node*> q;
  10.         vector<int> res;
  11.         Node *cur;
  12.         if(!root) {
  13.             return res;
  14.         }
  15.         int sz = 1;
  16.         q.push(root);
  17.         while(sz) {
  18.             cur = q.top();
  19.             sz--;
  20.             q.pop();
  21.             for(int i = cur->children.size()-1; i >= 0; i--) {
  22.                 q.push(cur->children[i]);
  23.                 sz++;
  24.             }
  25.             res.push_back(cur->val);
  26.         }
  27.         return res;
  28.     }
  29. };
Advertisement
Add Comment
Please, Sign In to add comment