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', ans=None) -> List[List[int]]:
"""
0
/ \
1 2
/ \
3 4
/ \
6 9
Pre-order...: [0, 1, 3, 4, 5, 9, 2]
"""
if not root:
return []
if ans is None:
ans = []
ans.append(root.val) # Pre-order Traversal
self.traversal(root.left, ans=ans)
self.traversal(root.right, ans=ans)
return ans
Iterative Implementation
root
➡️ left
➡️ right
class Solution:
def traversal(self, root: 'TreeNode')->List[List[int]]:
"""
0
/ \
1 2
/ \
3 4
/ \
6 9
Pre-order...: [0, 1, 3, 4, 5, 9, 2]
"""
if not root:
return root
stack = [root]
results = []
while stack:
node = stack.pop()
if node:
results.append(node.val)
stack.append(node.right)
stack.append(node.left)
return results