jayati

N-ary Tree Preorder Traversal

Oct 9th, 2022
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.98 KB | None | 0 0
  1. /*
  2. // Definition for a Node.
  3. class Node {
  4. public:
  5.     int val;
  6.     vector<Node*> children;
  7.  
  8.     Node() {}
  9.  
  10.     Node(int _val) {
  11.         val = _val;
  12.     }
  13.  
  14.     Node(int _val, vector<Node*> _children) {
  15.         val = _val;
  16.         children = _children;
  17.     }
  18. };
  19. */
  20.  
  21. class Solution {
  22. public:
  23.     vector<int> preorder(Node* root) {
  24.        stack<Node*> Stack;
  25.  
  26.     // 'Preorder'-> contains all the
  27.     // visited nodes
  28.     vector<int> Preorder;
  29.     if(root==nullptr)
  30.     {
  31.         return Preorder;
  32.     }
  33.     Stack.push(root);
  34.    
  35.     while (!Stack.empty()) {
  36.         Node* temp = Stack.top();
  37.         Stack.pop();
  38.         // store the key in preorder vector(visited list)
  39.         Preorder.push_back(temp->val);
  40.         // Push all of the child nodes of temp into
  41.         // the stack from right to left.
  42.         for (int i = temp->children.size() - 1; i >= 0; i--) {
  43.             Stack.push(temp->children[i]);
  44.         }
  45.     }
  46.     return Preorder;
  47.     }
  48. };
Advertisement
Add Comment
Please, Sign In to add comment