class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
output = []
def dfs(root):
if not root:
return
dfs(root.left)
output.append(root.val)
dfs(root.right)
dfs(root)
return output
Iterative Code
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
result = []
stack = []
current = root
while current or stack:
while current:
stack.append(current)
current = current.left
current = stack.pop()
result.append(current.val)
current = current.right
return result