Professional Documents
Culture Documents
Date: _____________
Artificial intelligence
(LAB)
Lab Task # 5
1. Lab Task 1
Implement Trees in python
Code:
class Tree:
self.left = left
self.right = right
self.value = value
def PrintTree(self):
print(self.value)
if self.left:
self.left.PrintTree()
if self.right:
self.right.PrintTree()
root.PrintTree()
Output:
2. Lab Task 2
Implement Stack in python
Code:
stack = []
stack.append('a')
stack.append('b')
stack.append('c')
print('Initial stack')
print(stack)
Output:
3. Lab Task 3
Implement Binary Trees in python
Code:
class BinaryTreeNode:
def __init__(self, data):
self.data = data
self.leftChild = None
self.rightChild = None
a1=BinaryTreeNode(10)
a2=BinaryTreeNode(15)
a3=BinaryTreeNode(20)
a4=BinaryTreeNode(60)
a5=BinaryTreeNode(14)
a6=BinaryTreeNode(25)
a7=BinaryTreeNode(6)
a1.leftChild=a2
a1.rightChild=a3
a2.leftChild=a4
a2.rightChild=a5
a3.leftChild=a6
a3.rightChild=a7
print("Node is:")
print(a2.data)
print("Node is:")
print(a3.data)
print("Node is:")
print(a4.data)
print("Node is:")
print(a5.data)
print("Node is:")
print(a6.data)
print("Node is:")
print(a7.data)
Output:
4. Lab Task 4
Implement DFS Algorithm in python
Code:
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
print(start)
dfs(graph, '0')
Output:
5. Lab Task 5
Implement Pre order, In order and Post order traversals in DFS.
Code:
class Node:
def __init__(self,key):
self.left = None
self.right = None
self.val = key
def printInorder(root):
if root:
printInorder(root.left)
print(root.val)
printInorder(root.right)
def printPostorder(root):
if root:
printPostorder(root.left)
printPostorder(root.right)
print(root.val)
def printPreorder(root):
if root:
print(root.val)
printPreorder(root.left)
printPreorder(root.right)
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print("Preorder traversal of binary tree is")
printPreorder(root)
Output: