Posts

Showing posts with the label tree

CREATE A BINARY TREE OF INTEGERS : BINARY SEARCH TREE

 # Formulate a program to create a binary tree of integers in python class Node:     def __init__(self, data):         self.left = None         self.right = None         self.data = data     def insert(self, data): # Compare the new value with the parent node         if self.data:             if data < self.data:                 if self.left is None:                     self.left = Node(data)                 else:                  ...

TRAVERSE INORDER PREORDER POSTORDER : BINARY SEARCH TREE

 # traverse inorder, preorder, postorder class Node(object):     def __init__(self,value):         self.value=value         self.left=None         self.right=None class BinaryTree(object):     def __init__(self,root):         self.root=Node(root)     def print_tree(self,traversal_type):         if traversal_type=="preorder":             return self.preorder_print(tree.root, "")             elif traversal_type=="inorder":             return self.inorder_print(tree.root, "")             if traversal_type=="postorder":             return self.postorder_print(tree.root, "")...

TRAVERSING IN PREORDER INORDER AND POSTORDER USING STACK : BINARY SEARCH TREE

 ## Compose a non-recursive program, for traversing, a binary tree in preorder, inorder, and postorder? ## Using stack class Node:     def __init__(self,data):         self.data=data         self.left=None         self.right=None         self.visited=False def Postorder(rootNode):     nodeStack=[]     nodeStack.append(rootNode)     while (not (len(nodeStack)==0)):         currNode = nodeStack[len(nodeStack)-1]         if ((currNode.left != None) and (currNode.left.visited == False)):             nodeStack.append(currNode.left)         else:             if ((currNode.right != None) and (currNode.right.visited == False)):  ...

IF A TREE IS HEIGHT-BALANCED OR NOT : BINARY SEARCH TREE

 """ Python3 program to check if a tree is height-balanced """ # A binary tree Node class Node:     # Constructor to create a new Node     def __init__(self, data):         self.data = data         self.left = None         self.right = None   # function to find height of binary tree def height(root):            # base condition when binary tree is empty     if root is None:         return 0     return max(height(root.left), height(root.right)) + 1   # function to check if tree is height-balanced or not def isBalanced(root):            # Base condition     if root is None:         return True       # for left and right subtree he...