Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Runtime: 144 ms, faster than 90.97% of C++ online submissions for N-ary Tree Preorder Traversal.
- Memory Usage: 33.2 MB, less than 21.05% of C++ online submissions for N-ary Tree Preorder Traversal.
- */
- class Solution {
- public:
- vector<int> preorder(Node* root) {
- stack<Node*> q;
- vector<int> res;
- Node *cur;
- if(!root) {
- return res;
- }
- int sz = 1;
- q.push(root);
- while(sz) {
- cur = q.top();
- sz--;
- q.pop();
- for(int i = cur->children.size()-1; i >= 0; i--) {
- q.push(cur->children[i]);
- sz++;
- }
- res.push_back(cur->val);
- }
- return res;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment