Re: [闲聊] 每日leetcode

楼主: dont   2024-08-26 15:40:36
590. N-ary Tree Postorder Traversal
## 思路
跟昨天的一样
Iter1. 照顺序加到stack, 最后再把结果reverse
Iter2. child反顺序加进stack, 记录node有没有走过, 走过才加进res
## Code
Iter1
```python
class Solution:
def postorder(self, root: 'Node') -> List[int]:
if not root:
return []
res = []
stack = [root]
while stack:
node = stack.pop()
res.append(node.val)
for child in node.children:
stack.append(child)
return res[::-1]
```
Iter2
```python
class Solution:
def postorder(self, root: 'Node') -> List[int]:
if not root:
return []
res = []
stack = [(root, False)]
while stack:
curr, is_visited = stack.pop()
if is_visited:
res.append(curr.val)
else:
stack.append((curr, True))
for child in reversed(curr.children):
stack.append((child, False))
return res
```
作者: DJYOMIYAHINA (通通打死)   2024-08-26 15:41:00
剩我只会写recursive了
作者: oin1104 (是oin的说)   2024-08-26 15:42:00
我是大便

Links booklink

Contact Us: admin [ a t ] ucptt.com