Skip to content

Instantly share code, notes, and snippets.

@siavashk
Last active November 30, 2024 21:19
Show Gist options
  • Save siavashk/404cbed0157d8da01c8dc7ab754fd3cc to your computer and use it in GitHub Desktop.
Save siavashk/404cbed0157d8da01c8dc7ab754fd3cc to your computer and use it in GitHub Desktop.
DFS Recursive Binary Tree Traversal
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
def recursive_inorder_traversal(root: TreeNode):
if not root:
return
left = recursive_inorder_traversal(root.left)
# This where we process the node.
# Notice we do left -> root -> right
print(root.val)
right = recursive_inorder_traversal(root.right)
return
def recursive_preorder_traversal(root: TreeNode):
if not root:
return
# This where we process the node.
# Notice we do root -> left -> right
print(root.val)
left = recursive_inorder_traversal(root.left)
right = recursive_inorder_traversal(root.right)
return
def recursive_postorder_traversal(root: TreeNode):
if not root:
return
# This where we process the node.
# Notice we do root left -> right -> root
left = recursive_inorder_traversal(root.left)
right = recursive_inorder_traversal(root.right)
print(root.val)
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment