-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostorderTraversal.py
39 lines (32 loc) · 1023 Bytes
/
PostorderTraversal.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# Recursive
class Solution:
def __init__(self):
self.res = []
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
self._postorder(root)
return self.res
def _postorder(self, root: Optional[TreeNode]) -> None:
if root is None:
return
self._postorder(root.left)
self._postorder(root.right)
self.res.append(root.val)
# Iterative
class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
stack = [root]
visit = [False]
res = []
while stack:
cur, v = stack.pop(), visit.pop()
if cur:
if v:
res.append(cur.val)
else:
stack.append(cur)
visit.append(True)
stack.append(cur.right)
visit.append(False)
stack.append(cur.left)
visit.append(False)
return res