In case of dfs we will go as deep as possible in the given tree. In BFS we have explored or processed the nodes at the same level then we move further, but that is not the case when we consider DFS.
In DFS we will pick a node then we will pick it's child node(if any) then it's child and so on until we reaches the leaf node.
Let's consider the same tree we constructed in breadth first search post.
When we talk about traversing a binary tree with depth first search technique then we have tree type of dfs traversal.
- In Order (left subtree -> current node -> right subtree)
- Pre Order (current node-> left subtree -> right subtree)
- Post Order (left subtree -> right subtree -> current node)
Algotuthm For Iterative:
- We start with the root node and check that, if root is null then we sipmly return.
- Otherwise we will create a hashset to keep track of the visited nodes.
- We will be required a stack to push the nodes to process them 1 by 1.
- Add the current node in the stack to start the traversal.
- Get the top element and check if it doesn't have left or right subtree then process(print) it.
- If we have processed all the left subtree then print the current node.
- Otherwise add the current node in the visited nodes set i.e we visit the current node and mark it as visited.
- Now add current node's right subtree in the stack.
- Add the current node in the stack
- Add the left subtree in the stack
- Perform step 5 thorough step 10 until stack is empty i.e. all the nodes have been visited and processed.
Algorithm For Recursion:
- We start with the root node and check that, if root is null then we sipmly return.
- We will process the left subtree, current node and right subtree based on the type of traversal we want.
Adding into the stack order for Iterative method :
**Time Complexity of BFS = O(V+E) where V is vertices and E is edges. Time Complexity of DFS is also O(V+E) where V is vertices and E is edges.
0 Comments