-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary Tree Postorder Traversal.py
More file actions
38 lines (27 loc) · 1013 Bytes
/
Binary Tree Postorder Traversal.py
File metadata and controls
38 lines (27 loc) · 1013 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
37
38
# https://leetcode.com/problems/binary-tree-postorder-traversal/
# 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 postorder(self, root, nodes):
# If root is empty, exit function
if root is None:
return
# Visit children
self.postorder(root.left, nodes)
self.postorder(root.right, nodes)
# Add root to list
nodes.append(root.val)
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
# OBJECTIVE: Traverse tree in postorder order (left, right, root)
# If root is empty, return an empty list
if root is None:
return list()
# Create a list
nodes = list()
# Traverse tree
self.postorder(root, nodes)
return nodes