N-ary Tree Postorder Traversal - Leetcode 590 - Python

NeetCodeIO · Intermediate ·⚡ Algorithms & Data Structures ·1y ago

Key Takeaways

The video demonstrates how to solve the Leetcode 590 problem, N-ary Tree Postorder Traversal, using both recursive and iterative approaches in Python, covering time and space complexity, and providing step-by-step solutions.

Full Transcript

hey everyone welcome back and let's write some more neat code today so today let's solve the problem Nary tree post order traversal so the idea is basically if you know what a regular tree is well when I say regular I mean binary that's kind of the most common where each node will have at most two children so something like this well we could relax that constraint of having two children and allow multiple children so zero children one children two and then more than that so 3 four five it could be unbounded so what kind of data structure do you think we should use to store all of the children of a particular node well we can't just have one or two variables for that anymore so now we probably need something like an array and that's exactly what we're going to have in most languages we're going to have like a resizable list as the children variable for a node object now so imagine you have multiple children for a node well now how do you do the postorder traversal remember post order traversal just means you will only visit a node after all of its children have been visited and that's going to be recursive so that applies for all of these nodes as well so basically we're going to do all of the descendants of a single node and then we'll pop back up to the parent and then do all the other descendants of that node and then we'll do the parent recursively with two nodes with postorder reversal what we would do is do the left child then recursively do the right child and then lastly do the current node so the only thing that's going to change from here to the general tree is that these two steps are actually going to be merged into a single step and that's going to be run a helper function or just recursively on the children all of them and I think the order does matter so we probably want to do the leftmost child first and then the next one and then the next one so do that and then lastly or the second step really is just the original node so it's pretty much the same recursively I'll also do this iteratively for you as well the time and space complexity I think is going to be the same but let's solve this this recursively now so I'm going to create the helper function down here and that's what I'm going to call it we're going to be given a current node the base case is the same as like pretty much every recursive tree problem so if not node then just return there's no need to return anything because what we want to do is basically collect all the values of every node and then put them in a list and then return that so from here we could return an empty list from here and then do a bunch of joining with the recursive call but I think it's probably just easier to have like a variable like this result and then we can just return that out here and then within the function we can modify that we could have made it a member variable if we needed to but I didn't so here remember there's two steps we're going to go through every child so for a child in node. that is the data type that's given to us I think it should be a list type but in Python it's kind of ambiguous and then so for all the children we're going to run the helper function recursively on them and then after that's done to the result we want to append the current nodes value so node do value with this problem I think we could have just gotten the return values from here and then joined them into a single list but that wouldn't have been as efficient and it would have been more complicated to code that up as well so this is I think the working solution let's run it okay well I promise you it would be the working solution if we didn't forget to actually call the helper function so let me do that on the root really sorry about that okay there you go it works this is technically the most efficient solution we're just going to go through every node in the tree so in terms of the uh time complexity would have been Big O of n in terms of the memory complexity it still would have been Big O of H where H is the height of the tree for a balanced tree it should be log n it should be log where the base is I guess the branching Factor if that's the correct term for this but anyways let's now do the iterative solution actually and I'll quickly walk you through how we're going to do it the time and space complexity though is going to be the same I just think it's interesting to solve this iteratively sometimes that can be asked in interviews so let's do it so we kind of just talked about how to do this recursively well doing it iteratively isn't too much different it's definitely not much different from just doing it on a regular binary tree but let's still imagine we have multiple children we have three children let's say so here we want to do this guy so if we were doing this iteratively usually we have a stack and that's what we're going to have this time but I'll just kind of spoil this for you this is in most languages going to require two stacks one stack where we actually add the node itself and then another stack where we Mark if that node has been visited or not that's going to be with a Boolean value and the reason for that is imagine we were just doing this pre-order style or even if we're doing this in order pre-order would be pretty easy that would mean taking this node visiting it and then we want to go through all of the children well that's what we're going to need the stack for because for us to say okay we go through all the children first we want to go to this child and then do all of its descendants and then eventually we want to come back here so that's what the stack would be for we wouldn't add this to the stack we would add these guys to the stack in that order well maybe this time it would be in reverse order because we'll pop the last thing that was added to the stack that would be pre-order in order would be pretty similar as well except that time we would add this to the stack and then go left and then eventually we'd pop back here and then we'd go right well with postorder it's a little bit unique I think post order is the hardest one to do even with just a regular binary tree and that's because when we get to this node we want to actually do this node last so how do we do that well we add this to the stack and then we go through its children okay but if you try that then you're going to go through the children you're going to end up adding let's say this guy also to the stack and then when you pop this from the stack there's no guarantee that all of its descendants has been like visited because we're going to be adding these guys first and then adding The Descendants since we're popping first in first out these are going to be popped before their children are popped so that's why we're going to have two stacks sometimes we're going to pop a node and it hasn't been visited before that's fine but once a node has already been visited and it's being visited for the second time that's when we know we're actually finished with that node so just to quickly dry run this I'll give some numbers to these nodes initially we're going to have uh the node one and we're going to say it hasn't been visited so it's false that's what we're going to pop first and then we're going to see that it was not already visited so this time we're going to add it back to the stack and this time we're going to mark it visited and we're going to take its children and then add them to the stack now too we're probably going to do it in reverse order so we'd do this four three I'm running out of space sorry and then two and then these would all be false and then we'd pop this one most recently that's why we added it last because it's two that's the one that we' want to go through first so we'd pop this we'd see this hasn't been visited yet either so we'd add it back to the stack and we'd add its children and you can continue with this eventually we'll have gone through all of these and then we'll get to this guy and this will be the last one that we pop this is the last item in our stack so it makes sense that it is the root of our tree so that's the idea let's go ahead and code this up okay so I'll actually leave this code here because I'm pretty sure my solution will be pretty similar so here I'm going to start the stack like this with just the root and we're going to say false it hasn't been visited yet and it's actually technically possible that the root could be null so my code isn't really going to handle that elegantly so I think the best way to handle that is just with an if statement so if not root go ahead and return an empty list otherwise let's go through the stack while stack we're going to pop so pop from this stack and we're going to get two values by the way in Python I am using a tuple a pair of values you could probably do that in other Lang as well that have like a pair class but if you wanted to you could also just have two separate Stacks they're always going to be of the same length anyway so that works too so we pop we get two things we get the node and we get if it's been visited or not if it's not been visited this is what we do or actually if it has already been visited that means this is the second time we're seeing it so then we're just going to take its value and append it to the result so result do append node. Val and you can see that this is actually analogous to what we did in the recursive solution down here technically the first time we see this node is when we start the recursive call and we check if it's null we return immediately then we go through all of its children and then we come back in the second time we see that same node that's when we actually append it to the result after we've gone through the children so that's what we're doing up here as well so we have one case where it was visited and we have the other case where it's not been visited so we're going to add it back to the stack so a stack. append this node but this time Market as visited so first it was false now it's going to be true and go through all of the children for C in node. children add them to the stack as well so see and mark them as false they haven't been visited this is the first time they're being added to the stack and then after all of this we can just return the result there's only one problem with this and remember it's the order the order that we add the children in does matter so I think in this case we want to do it in reverse order in Python that's pretty easy easy to fix here we can just add colon colon minus one this basically goes through the list in reverse order I think we're good here let's go ahead and run this and as you can see it works it's pretty efficient this is the iterative solution the time and space complexity I believe is the same if you found this helpful check out NE code. for a lot more thanks for watching and I'll see you soon

Original Description

🚀 https://neetcode.io/ - A better way to prepare for Coding Interviews 🧑‍💼 LinkedIn: https://www.linkedin.com/in/navdeep-singh-3aaa14161/ 🐦 Twitter: https://twitter.com/neetcode1 ⭐ BLIND-75 PLAYLIST: https://www.youtube.com/watch?v=KLlXCFG5TnA&list=PLot-Xpze53ldVwtstag2TL4HQhAnC8ATf Problem Link: https://leetcode.com/problems/n-ary-tree-postorder-traversal/description/ 0:00 - Read the problem 0:30 - Drawing Explanation 2:01 - Coding Explanation 4:04 - Drawing Explanation 7:23 - Coding Explanation leetcode 590 #neetcode #leetcode #python
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from NeetCodeIO · NeetCodeIO · 0 of 60

← Previous Next →
1 Leetcode 149 - Maximum Points on a Line - Python
Leetcode 149 - Maximum Points on a Line - Python
NeetCodeIO
2 Design Linked List - Leetcode 707 - Python
Design Linked List - Leetcode 707 - Python
NeetCodeIO
3 Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
NeetCodeIO
4 Design Browser History - Leetcode 1472 - Python
Design Browser History - Leetcode 1472 - Python
NeetCodeIO
5 Number of Good Paths - Leetcode 2421 - Python
Number of Good Paths - Leetcode 2421 - Python
NeetCodeIO
6 Flip String to Monotone Increasing - Leetcode 926 - Python
Flip String to Monotone Increasing - Leetcode 926 - Python
NeetCodeIO
7 Maximum Sum Circular Subarray - Leetcode 918 - Python
Maximum Sum Circular Subarray - Leetcode 918 - Python
NeetCodeIO
8 Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
NeetCodeIO
9 Concatenated Words - Leetcode 472 - Python
Concatenated Words - Leetcode 472 - Python
NeetCodeIO
10 Data Stream as Disjoint Intervals - Leetcode 352 - Python
Data Stream as Disjoint Intervals - Leetcode 352 - Python
NeetCodeIO
11 LFU Cache - Leetcode 460 - Python
LFU Cache - Leetcode 460 - Python
NeetCodeIO
12 N-th Tribonacci Number - Leetcode 1137
N-th Tribonacci Number - Leetcode 1137
NeetCodeIO
13 Best Team with no Conflicts - Leetcode 1626 - Python
Best Team with no Conflicts - Leetcode 1626 - Python
NeetCodeIO
14 Greatest Common Divisor of Strings - Leetcode 1071 - Python
Greatest Common Divisor of Strings - Leetcode 1071 - Python
NeetCodeIO
15 Shortest Path in a Binary Matrix - Leetcode 1091 - Python
Shortest Path in a Binary Matrix - Leetcode 1091 - Python
NeetCodeIO
16 Insert into a Binary Search Tree - Leetcode 701 - Python
Insert into a Binary Search Tree - Leetcode 701 - Python
NeetCodeIO
17 Delete Node in a BST - Leetcode 450 - Python
Delete Node in a BST - Leetcode 450 - Python
NeetCodeIO
18 Shuffle the Array (Constant Space) - Leetcode 1470 - Python
Shuffle the Array (Constant Space) - Leetcode 1470 - Python
NeetCodeIO
19 Fruits into Basket - Leetcode 904 - Python
Fruits into Basket - Leetcode 904 - Python
NeetCodeIO
20 Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
NeetCodeIO
21 Naming a Company - Leetcode 2306 - Python
Naming a Company - Leetcode 2306 - Python
NeetCodeIO
22 As Far from Land as Possible - Leetcode 1162 - Python
As Far from Land as Possible - Leetcode 1162 - Python
NeetCodeIO
23 Shortest Path with Alternating Colors - Leetcode 1129 - Python
Shortest Path with Alternating Colors - Leetcode 1129 - Python
NeetCodeIO
24 Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
NeetCodeIO
25 Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
NeetCodeIO
26 Contains Duplicate II - Leetcode 219 - Python
Contains Duplicate II - Leetcode 219 - Python
NeetCodeIO
27 Path with Maximum Probability - Leetcode 1514 - Python
Path with Maximum Probability - Leetcode 1514 - Python
NeetCodeIO
28 Add to Array-Form of Integer - Leetcode 989 - Python
Add to Array-Form of Integer - Leetcode 989 - Python
NeetCodeIO
29 Unique Paths II - Leetcode 63 - Python
Unique Paths II - Leetcode 63 - Python
NeetCodeIO
30 Minimum Distance between BST Nodes - Leetcode 783 - Python
Minimum Distance between BST Nodes - Leetcode 783 - Python
NeetCodeIO
31 Design Hashmap - Leetcode 706 - Python
Design Hashmap - Leetcode 706 - Python
NeetCodeIO
32 Range Sum Query Immutable - Leetcode 303 - Python
Range Sum Query Immutable - Leetcode 303 - Python
NeetCodeIO
33 Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
NeetCodeIO
34 Middle of the Linked List - Leetcode 876 - Python
Middle of the Linked List - Leetcode 876 - Python
NeetCodeIO
35 Course Schedule IV - Leetcode 1462 - Python
Course Schedule IV - Leetcode 1462 - Python
NeetCodeIO
36 Single Element in a Sorted Array - Leetcode 540 - Python
Single Element in a Sorted Array - Leetcode 540 - Python
NeetCodeIO
37 Capacity to Ship Packages - Leetcode 1011 - Python
Capacity to Ship Packages - Leetcode 1011 - Python
NeetCodeIO
38 IPO - Leetcode 502 - Python
IPO - Leetcode 502 - Python
NeetCodeIO
39 Minimize Deviation in Array - Leetcode 1675 - Python
Minimize Deviation in Array - Leetcode 1675 - Python
NeetCodeIO
40 Longest Turbulent Array - Leetcode 978 - Python
Longest Turbulent Array - Leetcode 978 - Python
NeetCodeIO
41 Last Stone Weight II - Leetcode 1049 - Python
Last Stone Weight II - Leetcode 1049 - Python
NeetCodeIO
42 Construct Quad Tree - Leetcode 427 - Python
Construct Quad Tree - Leetcode 427 - Python
NeetCodeIO
43 Find Duplicate Subtrees - Leetcode 652 - Python
Find Duplicate Subtrees - Leetcode 652 - Python
NeetCodeIO
44 Sort an Array - Leetcode 912 - Python
Sort an Array - Leetcode 912 - Python
NeetCodeIO
45 Ones and Zeroes - Leetcode 474 - Python
Ones and Zeroes - Leetcode 474 - Python
NeetCodeIO
46 Remove Duplicates from Sorted Array II - Leetcode 80 - Python
Remove Duplicates from Sorted Array II - Leetcode 80 - Python
NeetCodeIO
47 Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
NeetCodeIO
48 Concatenation of Array - Leetcode 1929 - Python
Concatenation of Array - Leetcode 1929 - Python
NeetCodeIO
49 Symmetric Tree - Leetcode 101 - Python
Symmetric Tree - Leetcode 101 - Python
NeetCodeIO
50 Check Completeness of a Binary Tree - Leetcode 958 - Python
Check Completeness of a Binary Tree - Leetcode 958 - Python
NeetCodeIO
51 Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
NeetCodeIO
52 Find Peak Element - Leetcode 162 - Python
Find Peak Element - Leetcode 162 - Python
NeetCodeIO
53 Accounts Merge - Leetcode 721 - Python
Accounts Merge - Leetcode 721 - Python
NeetCodeIO
54 Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
NeetCodeIO
55 Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
NeetCodeIO
56 Number of Zero-Filled Subarrays - Leetcode 2348 - Python
Number of Zero-Filled Subarrays - Leetcode 2348 - Python
NeetCodeIO
57 Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
NeetCodeIO
58 Sqrt(x) - Leetcode 69 - Python
Sqrt(x) - Leetcode 69 - Python
NeetCodeIO
59 Successful Pairs of Spells and Potions - Leetcode 2300 - Python
Successful Pairs of Spells and Potions - Leetcode 2300 - Python
NeetCodeIO
60 Optimal Partition of String - Leetcode 2405 - Python
Optimal Partition of String - Leetcode 2405 - Python
NeetCodeIO

This video teaches how to solve the N-ary Tree Postorder Traversal problem using recursive and iterative approaches in Python, covering the trade-offs between time and space complexity. The problem is relevant to systems design and algorithm basics.

Key Takeaways
  1. Create a helper function to perform recursive traversal
  2. Use two stacks to keep track of nodes and visited status in iterative solution
  3. Pop nodes from the stack in reverse order and add children to the stack
  4. Repeat the process until the stack is empty
💡 The iterative solution using two stacks can be more efficient than the recursive approach for large trees, as it avoids the overhead of recursive function calls.

Related AI Lessons

Bloom Filters, Explained Properly
Learn how Bloom filters work and their benefits, including tiny memory and blazing speed, in exchange for potential false positives.
Dev.to · Daksh Gargas
Prefix Sums: The Preprocessing Trick That Makes Range Queries Instant
Learn how prefix sums enable instant range queries in arrays, boosting performance in various applications
Medium · Programming
I Thought I Was Ready for the Interview — Then One Simple Math Question Destroyed Me
A simple math question can destroy a developer's interview, highlighting the importance of being prepared for unexpected questions
Medium · Programming
Week 2(Day 10): LeetCode Two Pointers(slow & fast): Remove Duplicates from Sorted Array (Brute…
Learn to remove duplicates from a sorted array using the two pointers technique, improving from brute force to optimized solutions
Medium · Python

Chapters (5)

Read the problem
0:30 Drawing Explanation
2:01 Coding Explanation
4:04 Drawing Explanation
7:23 Coding Explanation
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →