Re: [閒聊] 每日leetcode
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
```
---
545. Boundary of Binary Tree
## 思路
建三個array存 left boundary, leaves, right boundary
回傳 [root] + left + leaves + reverse right
node會有LEFT, RIGHT, MIDDLE三種type 按照題目列的case更改type
recur傳node跟node的type
## Code
```python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def boundaryOfBinaryTree(self, root: Optional[TreeNode]) -> List[int]:
LEFT, MIDDLE, RIGHT = 1, 2, 3
left, leaf, right = [], [], []
def recur(node, n_type):
if not node:
return
if not node.left and not node.right:
leaf.append(node.val)
return
if n_type == LEFT:
left.append(node.val)
elif n_type == RIGHT:
right.append(node.val)
if node.left:
if n_type == LEFT:
recur(node.left, LEFT)
elif n_type == RIGHT and not node.right:
recur(node.left, RIGHT)
else:
recur(node.left, MIDDLE)
if node.right:
if n_type == RIGHT:
recur(node.right, RIGHT)
elif n_type == LEFT and not node.left:
recur(node.right, LEFT)
else:
recur(node.right, MIDDLE)
recur(root.left, LEFT)
recur(root.right, RIGHT)
return [root.val] + left + leaf + right[::-1]
```
--
http://i.imgur.com/OLvBn3b.jpg

--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 185.213.82.184 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1724658039.A.9F1.html
推
08/26 15:41,
1年前
, 1F
08/26 15:41, 1F
推
08/26 15:42,
1年前
, 2F
08/26 15:42, 2F
討論串 (同標題文章)
完整討論串 (本文為第 767 之 1548 篇):