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

Python - List - Append, Count, Extend, Index, Insert, Pop, Remove, Reverse, Sort

🐍 Advance List List is widely used and it's functionalities are heavily useful. Append Adds one element at the end of the list. Syntax list1.append(value) Input l1 = [1, 2, 3] l1.append(4) l1 Output [1, 2, 3, 4] append can be used to add any datatype in a list. It can even add list inside list. Caution: Append does not return anything. It just appends the list. Count .count(value) counts the number of occurrences of an element in the list. Syntax list1.count(value) Input l1 = [1, 2, 3, 4, 3] l1.count(3) Output 2 It returns 0 if the value is not found in the list. Extend .count(value) counts the number of occurrences of an element in the list. Syntax list1.extend(list) Input l1 = [1, 2, 3] l1.extend([4, 5]) Output [1, 2, 3, 4, 5] If we use append, entire list will be added to the first list like one element. Extend, i nstead of considering a list as one element, it joins the two lists one after other. Append works in the following way. Input l1 = [1, 2, 3] l1.append([4, 5]) Output...

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.

683 K Empty Slots

  Approach #1: Insert Into Sorted Structure [Accepted] Intuition Let's add flowers in the order they bloom. When each flower blooms, we check it's neighbors to see if they can satisfy the condition with the current flower. Algorithm We'll maintain  active , a sorted data structure containing every flower that has currently bloomed. When we add a flower to  active , we should check it's lower and higher neighbors. If some neighbor satisfies the condition, we know the condition occurred first on this day. Complexity Analysis Time Complexity (Java):  O(N \log N) O ( N lo g N ) , where  N N  is the length of  flowers . Every insertion and search is  O(\log N) O ( lo g N ) . Time Complexity (Python):  O(N^2) O ( N 2 ) . As above, except  list.insert  is  O(N) O ( N ) . Space Complexity:  O(N) O ( N ) , the size of  active . Approach #2: Min Queue [Accepted] Intuition For each contiguous block ("window") of  k  po...