import queue
class BinaryTreeNode():
    def __init__(self,data):
        self.data=data
        self.left=None
        self.right=None
'''btn1=BinaryTreeNode(1)
btn2=BinaryTreeNode(2)
btn3=BinaryTreeNode(3)
btn4=BinaryTreeNode(4)
btn5=BinaryTreeNode(5)
btn6=BinaryTreeNode(6)

btn1.left=btn2
btn1.right=btn3
btn2.left=btn4
btn2.right=btn5
btn3.right=btn6'''

def PrintTreePreorderTraversal(root):
    if root == None:
        return
    print(root.data,end=" ")
    PrintTreePreorderTraversal(root.left)
    PrintTreePreorderTraversal(root.right)
def largestdata(root):
    if root == None:
        return -1
        
    leftlargest=largestdata(root.left)
    rightlargest=largestdata(root.right)
    return max(leftlargest,rightlargest,root.data)

def countNodesGreaterThanX(root, x):
    # Given a Binary Tree and an integer x, find and return the count of nodes
    # which are having data greater than x.
    #############################
    # PLEASE ADD YOUR CODE HERE #
    #############################
    if root is None:
        return 0

    leftNode=countNodesGreaterThanX(root.left,x)
    rightNode=countNodesGreaterThanX(root.right,x)
    if root.data>x:
        return 1+leftNode+rightNode
    return leftNode+rightNode
def numnodes(root):
    if root == None:
        return 0
    leftcount=numnodes(root.left)
    rightcount=numnodes(root.right)
    return 1+leftcount+rightcount
def sumnodes(root):
    if root==None:
        return 0
    leftsum=sumnodes(root.left)
    rightsum=sumnodes(root.right)
    return leftsum+rightsum+root.data
def heightofthetree(root):
    if root == None:
        return 0
    leftheight=heightofthetree(root.left)
    rightheight=heightofthetree(root.right)
    height=max(leftheight,rightheight)
    return 1+height
def numleafnodes(root):
    if root == None:
        return 0
    if root.left is None and root.right is None:
        return 1
    leftleafnodes=numleafnodes(root.left)
    rightleafnodes=numleafnodes(root.right)
    return leftleafnodes+rightleafnodes
def printdepthk(root,k):
    if root == None:
        return
    if k==0:
        print(root.data)
        return
    printdepthk(root.left,k-1)
    printdepthk(root.right,k-1)
def printdepthkv2(root,k, d = 0):
    if root == None:
        return
    if k == d:
        print(root.data)
        return
    printdepthkv2(root.left,k,d+1)
    printdepthkv2(root.right,k,d+1)
def changetree(root,k=0,d=0):
    if root == None:
        return
    changetree(root.left,k+1,d+1)
    changetree(root.right,k+1,d+1)
    if k ==d:
        root.data=d
        return 
def nodepresent(root,x):
    if root == None:
        return False
    if root.data == x:
        return True
    res1=nodepresent(root.left,x)
    if res1:
        return True
    res2=nodepresent(root.right,x)
    return res2
def ifNodeExists(node, key):
 
    if (node == None):
        return False
 
    if (node.data == key):
        return True
 
    """ then recur on left subtree """
    res1 = ifNodeExists(node.left, key)
    # node found, no need to look further
    if res1:
        return True
 
    """ node is not found in left,
    so recur on right subtree """
    res2 = ifNodeExists(node.right, key)
    return res2
def checksibling(root):
    if root == None:
        return 0
    if root.left==None and root.right==None:
        return -1
    if root.left!=None or root.right!=None:
        if root.left ==None:
            print(root.right.data,end=" ")
        if root.right ==None:
            print(root.left.data,end=" ")
    checksibling(root.left)
    checksibling(root.right)
def removeleafs(root):
    if root == None:
        return None
    if root.left is None and root.right is None:
        return None
    root.left=removeleafs(root.left)
    root.right=removeleafs(root.right)
    return root
def mirrortree(root):
    if root == None:
        return
    
    mirrortree(root.left)
    mirrortree(root.right)
    temp=root.left
    root.left=root.right
    root.right=temp
def isbalanced(root):
    if root == None:
        return True
    lh=heightofthetree(root.left)
    rh=heightofthetree(root.right)
    if lh-rh > 1 or rh - lh > 1:
        return False
    leftbalance=isbalanced(root.left)
    rightbalance=isbalanced(root.right)
    if leftbalance and rightbalance:
        return True
    else:
        return False
def heightanddiameter(root):
    if root == None:
        return 0,0
    lh,ld=heightanddiameter(root.left)
    rh,rd=heightanddiameter(root.right)
    h=1+max(lh,rh)
    a=lh+rh
    d=1+max(a,ld,rd)
    return h,d
def diameterofatree(root):
    heighting,diameter=heightanddiameter(root)
    return diameter


def buildtreefromprein(pre,inorder):
    if len(pre)==0:
        return None
    rootdata=pre[0]
    root=BinaryTreeNode(rootdata)
    rootindexininorder=-1
    for i in range(len(inorder)):
        if inorder[i]== rootdata:
            rootindexininorder=i
            break
    if rootindexininorder==-1:
        return None
    leftinorder=inorder[0:rootindexininorder]
    rightinorder=inorder[rootindexininorder+1:]
    lenleftsubtree=len(leftinorder)
    leftpreorder=pre[1:lenleftsubtree+1]
    rightpreorder=pre[lenleftsubtree+1:]
    leftchild=buildtreefromprein(leftpreorder,leftinorder)
    rightchild=buildtreefromprein(rightpreorder,rightinorder)
    root.left=leftchild
    root.right=rightchild
    return root
def buildtreefrompostin(post,inorder):
    if len(post)==0:
        return None
    rootdata=post[-1]
    root=BinaryTreeNode(rootdata)
    rootindexininorder=-1
    for i in range(len(inorder)):
        if inorder[i]== rootdata:
            rootindexininorder=i
            break
    if rootindexininorder==-1:
        return None
    leftinorder=inorder[0:rootindexininorder]
    rightinorder=inorder[rootindexininorder+1:]
    lenleftsubtree=len(leftinorder)
    leftpostorder=post[0:lenleftsubtree]
    rightpostorder=post[lenleftsubtree:len(post)-1]
    leftchild=buildtreefrompostin(leftpostorder,leftinorder)
    rightchild=buildtreefrompostin(rightpostorder,rightinorder)
    root.left=leftchild
    root.right=rightchild
    return root
def duplicateeverynode(root):
    if root == None:
        return None
    q=queue.Queue()
    print(root.data)
    print(root.left.data)
    q.put(root)
    while not q.empty():
        temp1=root.left
        temp2=root.data
        temp3=root.right
        currnode=q.get()
        newleft=BinaryTreeNode(currnode)
        newleft.left=temp2
        newleft1=BinaryTreeNode(newleft.left)
        if temp1 != None:
            newleft1.left=temp1
            q.put(temp1)
        if temp3 !=None:
            q.put(temp3)
def printtreelevelwisedetailed(root):
    if root == None:
        return
    q=queue.Queue()
    q.put(root)
    while not q.empty():
        currnode=q.get()
        print(currnode.data,end=":")
        if currnode.left != None:
            print('L:',end="")
            print(currnode.left.data,end=",")
        if currnode.left is None:
            print('L:-1',end=",")
        if currnode.right != None:
            print('R:',end="")
            print(currnode.right.data,end="")
        if currnode.right is None:
            print('R:-1',end="")
        print()
            
        if currnode.left is not None:
            q.put(currnode.left)
        if currnode.right is not None:
            q.put(currnode.right)
def treeinputlevelwise():
    q=queue.Queue()
    print('enter root')
    rootdata=int(input())
    if rootdata == -1:
        return None
    root=BinaryTreeNode(rootdata)
    q.put(root)
    while not q.empty():
        currnode=q.get()
        print('Enter leftchid data',currnode.data)
        leftdata=int(input())
        if leftdata!=-1:
            leftchild=BinaryTreeNode(leftdata)
            currnode.left=leftchild
            q.put(leftchild)
        print('Enter rightchid data',currnode.data)
        rightdata=int(input())
        if rightdata!=-1:
            rightchild=BinaryTreeNode(rightdata)
            currnode.right=rightchild
            q.put(rightchild)
    return root
def printtree(root):
    if root == None:
        return
    print(root.data,end=":")
    if root.left != None:
        print('L',root.left.data,end=" ")
    if root.right!=None:
        print('R',root.right.data,end="")
    print()
    printtree(root.left)
    printtree(root.right)
    
def TreeInput():
    rootdata=int(input())
    if rootdata==-1:
        return None
    root=BinaryTreeNode(rootdata)
    lefttree=TreeInput()
    righttree=TreeInput()
    root.left=lefttree
    root.right=righttree
    return root
root=treeinputlevelwise()
printtreelevelwisedetailed(root)
duplicateeverynode(root)
#post=[4,5,2,6,7,3,1]
#inorder=[4,2,5,1,6,3,7]
#root=buildtreefrompostin(post,inorder)
printtreelevelwisedetailed(root)
#root=TreeInput()
#print(diameterofatree(root))
#print(isbalanced(root))
#printtree(root)
#mirrortree(root)
#root=removeleafs(root)
#checksibling(root)
#print(nodepresent(root,5))
#changetree(root)
#printdepthk(root,2)
#printdepthk(root,2)
#print(numleafnodes(root))
#print(heightofthetree(root))
#print(countNodesGreaterThanX(root,9))
#print(largestdata(root))
#PrintTreePreorderTraversal(root)
#printtree(root)
#print(numnodes(root))
#print(sumnodes(root))










 
by

Python Online Compiler

Write, Run & Share Python code online using OneCompiler's Python online compiler for free. It's one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler's Python editor is easy and fast. The editor shows sample boilerplate code when you choose language as Python or Python2 and start coding.

Taking inputs (stdin)

OneCompiler's python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample python program which takes name as input and print your name with hello.

import sys
name = sys.stdin.readline()
print("Hello "+ name)

About Python

Python is a very popular general-purpose programming language which was created by Guido van Rossum, and released in 1991. It is very popular for web development and you can build almost anything like mobile apps, web apps, tools, data analytics, machine learning etc. It is designed to be simple and easy like english language. It's is highly productive and efficient making it a very popular language.

Tutorial & Syntax help

Loops

1. If-Else:

When ever you want to perform a set of operations based on a condition IF-ELSE is used.

if conditional-expression
    #code
elif conditional-expression
    #code
else:
    #code

Note:

Indentation is very important in Python, make sure the indentation is followed correctly

2. For:

For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.

Example:

mylist=("Iphone","Pixel","Samsung")
for i in mylist:
    print(i)

3. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while condition  
    #code 

Collections

There are four types of collections in Python.

1. List:

List is a collection which is ordered and can be changed. Lists are specified in square brackets.

Example:

mylist=["iPhone","Pixel","Samsung"]
print(mylist)

2. Tuple:

Tuple is a collection which is ordered and can not be changed. Tuples are specified in round brackets.

Example:

myTuple=("iPhone","Pixel","Samsung")
print(myTuple)

Below throws an error if you assign another value to tuple again.

myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
myTuple[1]="onePlus"
print(myTuple)

3. Set:

Set is a collection which is unordered and unindexed. Sets are specified in curly brackets.

Example:

myset = {"iPhone","Pixel","Samsung"}
print(myset)

4. Dictionary:

Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key - value pairs.

Example:

mydict = {
    "brand" :"iPhone",
    "model": "iPhone 11"
}
print(mydict)

Supported Libraries

Following are the libraries supported by OneCompiler's Python compiler

NameDescription
NumPyNumPy python library helps users to work on arrays with ease
SciPySciPy is a scientific computation library which depends on NumPy for convenient and fast N-dimensional array manipulation
SKLearn/Scikit-learnScikit-learn or Scikit-learn is the most useful library for machine learning in Python
PandasPandas is the most efficient Python library for data manipulation and analysis
DOcplexDOcplex is IBM Decision Optimization CPLEX Modeling for Python, is a library composed of Mathematical Programming Modeling and Constraint Programming Modeling