πŸ“ Problem Details

πŸ’­What Were My Initial Thoughts?

- the problem lies with it being an n-ary tree which makes the traversal order a little more complicated
- binary tree traversal: left->right->current node
- n-ary tree traversal: each child from left to right-> current node

πŸ€”What Did I Struggle With?

~

πŸ’‘ Explanation of Solution

- recursive solution
- init an empty result vector
- for each child in the roots children
	- construct a new vector that is the result of recursive call with the child as the param
	- insert that childResult into our result vector
- push the value of the current node into the result vector
- return the result

βŒ› Complexity Analysis

Time Complexity: O(n) where N nodes are traversed once
Space Complexity: O(n) due to the recursion call stack

πŸ’» Implementation of Solution

class Solution {
 
public:
Β  Β  vector<int> postorder(Node* root) {
Β  Β  Β  Β  if(root == nullptr) return {};
Β  Β  Β  Β  vector<int> result;
 
Β  Β  Β  Β  for (auto& child : root->children) {
Β  Β  Β  Β  Β  Β  vector<int> childResult = postorder(child);
Β  Β  Β  Β  Β  Β  result.insert(result.end(), childResult.begin(), childResult.end());
Β  Β  Β  Β  }
 
Β  Β  Β  Β  result.push_back(root->val); Β  Β // process the current nodes value
Β  Β  Β  Β  return result;
Β  Β  }
};