Last active
November 30, 2024 21:19
-
-
Save siavashk/404cbed0157d8da01c8dc7ab754fd3cc to your computer and use it in GitHub Desktop.
DFS Recursive Binary Tree Traversal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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