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