jayati

N-ary Tree Postorder Traversal

Oct 10th, 2022
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.95 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> postorder(Node* root) {
  24.         stack<Node*> Stack;
  25.        
  26.         vector<int> Postorder;
  27.         if(root==nullptr)
  28.         {
  29.             return Postorder;
  30.         }
  31.         Stack.push(root);
  32.         while(!Stack.empty())
  33.         {
  34.             Node* temp = Stack.top();
  35.             Stack.pop();
  36.             Postorder.push_back(temp->val);
  37.             for (int i = temp->children.size() - 1; i >= 0; i--)
  38.             {
  39.                 Stack.push(temp->children[(temp->children.size() - 1)-i]);
  40.             }
  41.            
  42.         }
  43.         reverse(Postorder.begin(),Postorder.end());
  44.         return Postorder;
  45.     }
  46. };
Advertisement
Add Comment
Please, Sign In to add comment