Created
February 15, 2020 06:03
-
-
Save manojnaidu619/578c0eb44e5033506280d54e1ed45bc2 to your computer and use it in GitHub Desktop.
Binary Trees implementation in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node: | |
def __init__(self): | |
self.data=None | |
self.left=None | |
self.right=None | |
class LL: | |
def __init__(self): | |
self.root=None | |
self.leaf=0 | |
def insert(self): | |
stack = [] | |
data = int(input("Enter the root tree data : ")) | |
node = Node() | |
self.root = node | |
node.data=data | |
stack.append(node) | |
while len(stack)>0: | |
child = stack.pop(0) | |
leafCount=0 | |
leftData=int(input("enter the left child data of {} : ".format(child.data))) | |
if leftData==-1: | |
child.left=None | |
leafCount+=1 | |
else: | |
node = Node() | |
node.data = leftData | |
child.left=node | |
stack.append(node) | |
rightData=int(input("enter the right child data of {} : ".format(child.data))) | |
if rightData==-1: | |
child.right=None | |
leafCount+=1 | |
else: | |
node = Node() | |
node.data = rightData | |
child.right=node | |
stack.append(node) | |
if leafCount==2: | |
self.leaf+=1 | |
def levelOrder(self): | |
root = self.root | |
stack = [] | |
stack.append(root) | |
while len(stack)>0: | |
child=stack.pop(0) | |
print(child.data) | |
if child.left: | |
stack.append(child.left) | |
if child.right: | |
stack.append(child.right) | |
def preOrder(self, root): | |
if root: | |
print(root.data) | |
self.preOrder(root.left) | |
self.preOrder(root.right) | |
ll = LL() | |
ll.insert() | |
ll.levelOrder() | |
print("Number of leaf node : ",ll.leaf) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment