Tree Node Definition
# Definition for a binary tree node.
from typing import List
class TreeNode:
def __init__(self, x: int) -> None:
self.val = x
self.left = None
self.right = None
Recursive Implementation
root
➡️ left
➡️ right
class Solution:
def traversal(self, root: 'TreeNode', out=None) -> List[List[int]]:
"""
0
/ \
1 2
/ \
3 4
/ \
6 9
Pre-order...: [0, 1, 3, 4, 5, 9, 2]
"""
if out is None:
out = []
if not root:
return []
out.append(root.val) # Pre-order Traversal
self.traversal(root.left, out=out)
self.traversal(root.right, out=out)
return out
Iterative Implementation
root
➡️ left
➡️ right
from collections import deque
class Solution:
def traversal(self, root: 'TreeNode', out=None)->List[List[int]]:
"""
0
/ \
1 2
/ \
3 4
/ \
6 9
Pre-order...: [0, 1, 3, 4, 5, 9, 2]
"""
if out is None:
out = []
if not root:
return []
stack = deque([root])
while stack:
node = stack.pop()
out.append(node.val)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return out