To understand the Depth-first search in the Binary tree, we first need to know why it is called the Depth-first search.

A binary tree is a hierarchical representation of nodes carrying data. Each node contains three fields, one for storing value which we would pass eventually, and the other two fields store address of the left and right child nodes.

Image for post

Just like every hierarchical structure, the tree also has one reference point. We call it root, which is the topmost node of the tree and has no parent node. In Binary tree, the root has at most two child nodes.

Image for post

If you noticed already, the tree is not a linear data structure, we cannot access nodes by indexing as we do in linear data structures(Array, List, Stack).

Then, how we would ever explore this complex-looking structure?

Here, tree traversal algorithms come to rescue. There are mainly two types of techniques we use to traverse a binary tree.

DEPTH FIRST SEARCH

BREADTH FIRST SEARCH

As the name implies, DFS traverse a tree by going in-depth recursively till it can and then backtracking to previously visited node. While BFS traverse a tree level by level.

Image for post

Imagine, you are in a maze game, you pick one road, mark that one visited so that you don’t visit it twice and, explore till you find the endpoint. Once you reach the endpoint, you go back to the previously visited road and start exploring from that point, repeat the procedure till you find the escape.

Well, DFS works exactly the same way.

There are three types of DFS in Tree

  • Preorder
  • Inorder
  • Postorder

Preorder:- Parent →Left →Right

Image for post

Inorder:- Left →Parent →Right

Image for post

#datastrucutre #coding #algorithms #python

DFS in Binary tree
1.45 GEEK