Skip to content

Commit 049e765

Browse files
My solution to 590
1 parent 0b50db2 commit 049e765

File tree

1 file changed

+35
-2
lines changed

1 file changed

+35
-2
lines changed

problems/590/jeremymanning.md

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,44 @@
11
# [Problem 590: N-ary Tree Postorder Traversal](https://leetcode.com/problems/n-ary-tree-postorder-traversal/description/?envType=daily-question)
22

33
## Initial thoughts (stream-of-consciousness)
4+
- This problem is the same as yesterday's, but with N-ary trees instead of binary trees
5+
- We can solve it the same way:
6+
- Execute a depth-first search, saving values to a list as we visit each node
7+
- Push the root, then the children (left to right) to the stack
8+
- At the end, return the list of values in reverse order
49

510
## Refining the problem, round 2 thoughts
11+
- The problem description doesn't say if all children are guaranteed to be non-null if there's a least one other non-null child of the given node. I guess we'll need to see what happens when we run the code.
612

713
## Attempted solution(s)
814
```python
9-
class Solution: # paste your code here!
10-
...
15+
"""
16+
# Definition for a Node.
17+
class Node:
18+
def __init__(self, val=None, children=None):
19+
self.val = val
20+
self.children = children
21+
"""
22+
23+
class Solution:
24+
def postorder(self, root: 'Node') -> List[int]:
25+
vals = []
26+
stack = [root]
27+
while stack:
28+
node = stack.pop()
29+
if node is not None:
30+
vals.append(node.val)
31+
if node.children is not None:
32+
for c in node.children:
33+
stack.append(c)
34+
return vals[::-1]
1135
```
36+
- Given test cases pass
37+
- Let's try some others:
38+
- `root = []`: pass
39+
- `root = [1, null, 2, 3, 4, 5, 6, 7, 8, null, 9, 10, 11, 12, null, 13, 14, 15, 16, 17, null, 18, 19, 20, null, null, 21, 22, 23, null, 24]`: pass
40+
- Ok; let's submit!
41+
42+
![Screenshot 2024-08-25 at 10 25 02 PM](https://github.com/user-attachments/assets/b8800303-2301-45f7-bbdc-9ef418d6a659)
43+
44+
Solved 🎉!

0 commit comments

Comments
 (0)