Specific way of visiting nodes in a tree.
Breadth-first search.
Depth-first search has three types:
Think about where the root
is positioned relative to left
and right
.
Time complexity: O(n)
where n
is the number of nodes in the tree.
Space complexity: O(h)
; where h
is the height of the tree (max number of function calls in the stack).
Steps
root
, to the right-most leaf node.root
Javascript:
function inOrderTraversal(node) { if (node !== null) { inOrderTraversal(node.left); visitNode(node); inOrderTraversal(node.right); } }
Python:
def in_order_traversal(root): if root is None: return # Traverse the left subtree in_order_traversal(root.left) # Visit the root node (Print the value) print(root.value, end=" ") # Traverse the right subtree in_order_traversal(root.right)
def pre_order_traversal(root): if root is None: return # Visit the root node (Print the value) print(root.value, end=" ") # Traverse the left subtree pre_order_traversal(root.left) # Traverse the right subtree pre_order_traversal(root.right)
def post_order_traversal(root): if root is None: return # Traverse the left subtree post_order_traversal(root.left) # Traverse the right subtree post_order_traversal(root.right) # Visit the root node (Print the value) print(root.value, end=" ")