-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBinaryTreePostorderTraversal.py
More file actions
36 lines (32 loc) · 972 Bytes
/
BinaryTreePostorderTraversal.py
File metadata and controls
36 lines (32 loc) · 972 Bytes
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
from typing import List
from collections import deque
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution1:
def postorderTraversal(self, root: TreeNode) -> List[int]:
result = []
self.helper(root, result)
return result
def helper(self, root, res):
if root:
self.helper(root.left, res)
self.helper(root.right, res)
res.append(root.val)
class Solution2:
def postorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
stack = [root]
result = deque()
while stack:
current = stack.pop()
result.appendleft(current.val)
if current.left:
stack.append(current.left)
if current.right:
stack.append(current.right)
return list(result)