#94. Binary Tree Inorder Traversal | LeetCode Python Solution
Problem
LeetCode Problem
- Binary Tree Inorder Traversal
Python Solution with Recursion
# 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:
# Inorder (Left, Root, Right)
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
# Handle base cases
if root is None:
return []
elif root.left is None and root.right is None:
return [root.val]
# Output list
output = []
# Collect left subtree values
if root.left is not None:
output = self.inorderTraversal(root.left)
# Collect root node value
output.append(root.val)
# Collect right subtree values
if root.right is not None:
output.extend(self.inorderTraversal(root.right))
return output