![]() |
VOOZH | about |
Depth-First Search (DFS) is a method used to explore all the nodes in a tree by going as deep as possible along each branch before moving to the next one. It starts at the root node and visits every node in the tree.
Depth-First Search (DFS) can be classified into three main types based on the order in which the nodes are visited:
- Traverse the left subtree, i.e., call Inorder(left-subtree)
- Visit the root
- Traverse the right subtree, i.e., call Inorder(right-subtree)
4 2 5 1 3 6
Time Complexity: O(N)
Auxiliary Space: O(log N)
In the case of binary search trees (BST), Inorder traversal gives nodes in non-decreasing order. To get nodes of BST in non-increasing order, a variation of Inorder traversal where Inorder traversal is reversed can be used.
- Visit the root
- Traverse the left subtree, i.e., call Preorder(left-subtree)
- Traverse the right subtree, i.e., call Preorder(right-subtree)
1 2 4 5 3 6
Time Complexity: O(N)
Auxiliary Space: O(log N)
Preorder traversal is used to create a copy of the tree. Preorder traversal is also used to get prefix expressions of an expression tree.
- Traverse the left subtree, i.e., call Postorder(left-subtree)
- Traverse the right subtree, i.e., call Postorder(right-subtree)
- Visit the root
4 5 2 6 3 1
Time Complexity: O(N)
Auxiliary Space: O(log N)
Postorder traversal is used to delete every node of the tree. Postorder traversal is also useful to get the postfix expression of an expression tree
Related Article : Breadth First Traversal.