590. N-ary Tree Postorder Traversal | Recursive + Iterative | Leetcode POTD Explained

  Рет қаралды 134

Jeevesh Rai

Jeevesh Rai

Күн бұрын

Пікірлер: 2
@codeby_naruto
@codeby_naruto 24 күн бұрын
Code:- Recursive Approach class Solution { public: // Helper function to perform post-order traversal void postOrder(Node *root, vector& res) { if (!root) return; // Base case: if root is null, return for (auto child : root->children) postOrder(child, res); // Recurse on children res.push_back(root->val); // Add current node's value to result } // Main function to initiate post-order traversal vector postorder(Node* root) { vector res; // Result vector to store the traversal postOrder(root, res); // Call helper function return res; // Return the result } }; Iterative Approach class Solution { public: vector postorder(Node* root) { if (!root) return {}; // Return empty vector if root is null stack stk; // Stack to manage nodes stk.push(root); // Push root node to stack vector res; // Vector to store post-order traversal while (!stk.empty()) { auto curr = stk.top(); // Get the current node stk.pop(); // Remove node from stack for (auto child : curr->children) stk.push(child); // Push children to stack res.push_back(curr->val); // Add current node's value to result } reverse(res.begin(), res.end()); // Reverse to get post-order return res; // Return result } };
@shubhamjaiswal7645
@shubhamjaiswal7645 24 күн бұрын
Brawl Stars Edit😈📕
00:15
Kan Andrey
Рет қаралды 46 МЛН
Modus males sekolah
00:14
fitrop
Рет қаралды 25 МЛН
Is Computer Science still worth it?
20:08
NeetCodeIO
Рет қаралды 129 М.
Top 7 Algorithms for Coding Interviews Explained SIMPLY
21:22
Codebagel
Рет қаралды 382 М.
OpenAI o1-preview answer unformalized physics questions
18:59
Ulf Rørbæk Pedersen
Рет қаралды 2,1 М.
iPhone 16 / 16 Pro Unboxing - Testing every new feature!
21:40
Mrwhosetheboss
Рет қаралды 2,6 МЛН
Learn Web Development And ACTUALLY Get A Job | Ultimate Guide
1:33:52
James Cross
Рет қаралды 1,3 МЛН
How I Mastered Data Structures and Algorithms
10:45
Ashish Pratap Singh
Рет қаралды 175 М.
Winning Codeforces Round 971 (Div. 4) in honor of @que_tourist
1:39:42
Making an Algorithm Faster
30:08
NeetCodeIO
Рет қаралды 30 М.