Skip to main content

How to Search Using Depth-First-Search (DFS) in Python?

Here is how to search using Depth-First-Search (DFS) in Python. There are three ways of implementing DFS - InOrder, PreOrder, and PostOrder.

  • InOrder Depth-First-Search gives output in ascending order
  • PreOrder Depth-First-Search gives output in order of traversing
  • PostOrder Depth-First-Search gives output in order of starting from the last left node, going rightwards and backwards
Suppose the following is the tree:

5
/ \
3 7
/ \ / \
2 4 6 8
/ \
1 10
/ \
9 15
/ \
13 19
/ \ / \
11 14 17 20
\ / \
12 16 18

Here is how all three Depth-First-Search would work
class BinaryTree:

def __init__(self):
self.reset()

def reset(self):
self.head = None
self.crawler = self.head

def push(self, value):

new_node = Node(value)
# if no head
if self.head == None:
self.head = new_node
print(f"{value} head")
# if head
else:
crawler = self.head
while True:
if value > crawler.value:
if crawler.child_right is None:
print(f"{value} right child of {crawler.value}")
crawler.child_right = new_node
break
else:
crawler = crawler.child_right
elif value < crawler.value:
if crawler.child_left is None:
print(f"{value} left child of {crawler.value}")
crawler.child_left = new_node
break
else:
crawler = crawler.child_left
else:
print(f"{value} already in Binary Tree")
break

def find(self, value):
if self.head is not None:
crawler = self.head
text = ""
while crawler:
if crawler.value > value:
text += str(crawler.value) + " then left "
crawler = crawler.child_left
elif crawler.value < value:
text += str(crawler.value) + " then right "
crawler = crawler.child_right
else:
text += "found " + str(crawler.value)
return text
return f"{value} not found"
return "No tree"
def remove(self, value):
if self.head is None:
return "Empty Tree"
else:
current_node = self.head
parent_node = None
while True:
if value < current_node.value:
parent_node = current_node
current_node = parent_node.child_left
elif value > current_node.value:
parent_node = current_node
current_node = parent_node.child_right
elif value == current_node.value:
if current_node.child_right == None:
if parent_node == None:
self.head = current_node.child_left
elif current_node.value < parent_node.value:
parent_node.child_left = current_node.child_left
elif current_node.value > parent_node.value:
parent_node.child_right = current_node.child_left
elif current_node.child_right.child_left == None:
if parent_node == None:
self.head = current_node.child_left
elif current_node.value < parent_node.value:
parent_node.child_right.child_left = current_node.child_left
elif current_node.value > parent_node.value:
parent_node.child_right = current_node.child_right
else:
leftmost = current_node.child_right.child_left
leftmostParent = current_node.child_right
while leftmost.child_left is not None:
leftmostParent = leftmost
leftmost = leftmost.child_left
leftmostParent.child_left = leftmost.child_right
leftmost.child_left = current_node.child_left
leftmost.child_right = current_node.child_right
if parent_node is None:
self.head = leftmost
else:
if current_node.value < parent_node.value:
parent_node.child_left = leftmost
elif current_node.value > parent_node.value:
parent_node.child_right = leftmost
return f"deleted {value}"
def dfsInorder(self):
return self.traverseInorder(self.head, [])

def traverseInorder(self, node, list1):
if node.child_left != None:
self.traverseInorder(node.child_left, list1)
list1.append(node.value)
if node.child_right != None:
self.traverseInorder(node.child_right, list1)
return list1
def dfsPreorder(self):
return self.traversePreorder(self.head, [])

def traversePreorder(self, node, list1):
list1.append(node.value)
if node.child_left != None:
self.traversePreorder(node.child_left, list1)
if node.child_right != None:
self.traversePreorder(node.child_right, list1)
return list1

def dfsPostorder(self):
return self.traversePostorder(self.head, [])

def traversePostorder(self, node, list1):
if node.child_left != None:
self.traversePostorder(node.child_left, list1)
if node.child_right != None:
self.traversePostorder(node.child_right, list1)
list1.append(node.value)
return list1


class Node:

def __init__(self, value):
self.value = value
self.parent = None
self.child_left = None
self.child_right = None


obj = BinaryTree()
obj.push(5)
obj.push(3)
obj.push(7)
obj.push(4)
obj.push(6)
obj.push(2)
obj.push(8)
obj.push(10)
obj.push(1)
obj.push(9)
obj.push(5)
obj.push(9)
obj.push(15)
obj.push(19)
obj.push(13)
obj.push(11)
obj.push(14)
obj.push(17)
obj.push(18)
obj.push(20)
obj.push(16)
obj.push(12)
print(obj.dfsInorder())
print(obj.dfsPreorder())
print(obj.dfsPostorder())
OUTPUT
5 head
3 left child of 5
7 right child of 5
4 right child of 3
6 left child of 7
2 left child of 3
8 right child of 7
10 right child of 8
1 left child of 2
9 left child of 10
5 already in Binary Tree
9 already in Binary Tree
15 right child of 10
19 right child of 15
13 left child of 15
11 left child of 13
14 right child of 13
17 left child of 19
18 right child of 17
20 right child of 19
16 left child of 17
12 right child of 11
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
[5, 3, 2, 1, 4, 7, 6, 8, 10, 9, 15, 13, 11, 12, 14, 19, 17, 16, 18, 20]
[1, 2, 4, 3, 6, 9, 12, 11, 14, 13, 16, 18, 17, 20, 19, 15, 10,8, 7, 5]

Comments

Popular posts from this blog

Difference between .exec() and .execPopulate() in Mongoose?

Here I answer what is the difference between .exec() and .execPopulate() in Mongoose? .exec() is used with a query while .execPopulate() is used with a document Syntax for .exec() is as follows: Model.query() . populate ( 'field' ) . exec () // returns promise . then ( function ( document ) { console . log ( document ); }); Syntax for .execPopulate() is as follows: fetchedDocument . populate ( 'field' ) . execPopulate () // returns promise . then ( function ( document ) { console . log ( document ); }); When working with individual document use .execPopulate(), for model query use .exec(). Both returns a promise. One can do without .exec() or .execPopulate() but then has to pass a callback in populate.

Machine Learning — Supervised, Unsupervised, and Reinforcement — Explanation with Example

🤖 Let's take an example of machine learning and see how it can be performed in three different ways — Supervised, Unsupervised, and Reinforcement. We want a program to be able to identify apple in pictures Supervised Learning You will create or use a model that takes a set of pictures of apple and it analyses the commonality in those pictures. Now when you show a new picture to the program, it will identify whether it has an apple or not. It can also provide details on how confident is the program about it. Unsupervised Learning In this method, you create or use a model that goes through some images and tries to group them as per the commonalities it observes such as color, shape, size, partern, etc. And now you can go through the groups and inform the program what to call them. So, you can inform the program about the group that is apple mostly. Next time you show a picture, it can tell if an apple is there or not. Reinforcement Learning Here the model you create or...

269. Alien Dictionary

  Solution This article assumes you already have some confidence with  graph algorithms , such as  breadth-first search  and  depth-first searching . If you're familiar with those, but not with  topological sort  (the topic tag for this problem), don't panic, as you should still be able to make sense of it. It is one of the many more advanced algorithms that keen programmers tend to "invent" themselves before realizing it's already a widely known and used algorithm. There are a couple of approaches to topological sort;  Kahn's Algorithm  and DFS. A few things to keep in mind: The letters  within a word  don't tell us anything about the relative order. For example, the presence of the word  kitten  in the list does  not  tell us that the letter  k  is before the letter  i . The input can contain words followed by their prefix, for example,  abcd  and then  ab . These cases will never ...