code
stringlengths 195
7.9k
| space_complexity
stringclasses 6
values | time_complexity
stringclasses 7
values |
|---|---|---|
# Python3 program to check children
# sum property
# Helper class that allocates a new
# node with the given data and None
# left and right pointers.
class newNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# returns 1 if children sum property
# holds for the given node and both
# of its children
def isSumProperty(node):
# left_data is left child data and
# right_data is for right child data
left_data = 0
right_data = 0
# If node is None or it's a leaf
# node then return true
if(node == None or (node.left == None and
node.right == None)):
return 1
else:
# If left child is not present then
# 0 is used as data of left child
if(node.left != None):
left_data = node.left.data
# If right child is not present then
# 0 is used as data of right child
if(node.right != None):
right_data = node.right.data
# if the node and both of its children
# satisfy the property return 1 else 0
if((node.data == left_data + right_data) and
isSumProperty(node.left) and
isSumProperty(node.right)):
return 1
else:
return 0
# Driver Code
if __name__ == '__main__':
root = newNode(10)
root.left = newNode(8)
root.right = newNode(2)
root.left.left = newNode(3)
root.left.right = newNode(5)
root.right.right = newNode(2)
# Function call
if(isSumProperty(root)):
print("The given tree satisfies the",
"children sum property ")
else:
print("The given tree does not satisfy",
"the children sum property ")
# This code is contributed by PranchalK
|
logn
|
linear
|
# Python program to check if two nodes in a binary
# tree are cousins
# A Binary Tree Node
class Node:
# Constructor to create a new Binary Tree
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def isSibling(root, a , b):
# Base Case
if root is None:
return 0
return ((root.left == a and root.right ==b) or
(root.left == b and root.right == a)or
isSibling(root.left, a, b) or
isSibling(root.right, a, b))
# Recursive function to find level of Node 'ptr' in
# a binary tree
def level(root, ptr, lev):
# Base Case
if root is None :
return 0
if root == ptr:
return lev
# Return level if Node is present in left subtree
l = level(root.left, ptr, lev+1)
if l != 0:
return l
# Else search in right subtree
return level(root.right, ptr, lev+1)
# Returns 1 if a and b are cousins, otherwise 0
def isCousin(root,a, b):
# 1. The two nodes should be on the same level in
# the binary tree
# The two nodes should not be siblings(means that
# they should not have the same parent node
if ((level(root,a,1) == level(root, b, 1)) and
not (isSibling(root, a, b))):
return 1
else:
return 0
# Driver program to test above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.left.right.right = Node(15)
root.right.left = Node(6)
root.right.right = Node(7)
root.right.left.right = Node(8)
node1 = root.left.right
node2 = root.right.right
print ("Yes" if isCousin(root, node1, node2) == 1 else "No")
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
|
linear
|
linear
|
# Python program to check if all leaves are at same level
# 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
# Recursive function which check whether all leaves are at
# same level
def checkUtil(root, level):
# Base Case
if root is None:
return True
# If a tree node is encountered
if root.left is None and root.right is None:
# When a leaf node is found first time
if check.leafLevel == 0 :
check.leafLevel = level # Set first leaf found
return True
# If this is not first leaf node, compare its level
# with first leaf's level
return level == check.leafLevel
# If this is not first leaf node, compare its level
# with first leaf's level
return (checkUtil(root.left, level+1)and
checkUtil(root.right, level+1))
def check(root):
level = 0
check.leafLevel = 0
return (checkUtil(root, level))
# Driver program to test above function
root = Node(12)
root.left = Node(5)
root.left.left = Node(3)
root.left.right = Node(9)
root.left.left.left = Node(1)
root.left.right.left = Node(2)
if(check(root)):
print "Leaves are at same level"
else:
print "Leaves are not at same level"
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
|
linear
|
linear
|
# Python3 program to check if all leaf nodes
# are at same level of binary tree
INT_MAX = 2**31
INT_MIN = -2**31
# Tree Node
# returns a new tree Node
class newNode:
def __init__(self, data):
self.data = data
self.left = self.right = None
# return true if all leaf nodes are
# at same level, else false
def checkLevelLeafNode(root) :
if (not root) :
return 1
# create a queue for level
# order traversal
q = []
q.append(root)
result = INT_MAX
level = 0
# traverse until the queue is empty
while (len(q)):
size = len(q)
level += 1
# traverse for complete level
while(size > 0 or len(q)):
temp = q[0]
q.pop(0)
# check for left child
if (temp.left) :
q.append(temp.left)
# if its leaf node
if(not temp.left.right and
not temp.left.left):
# if it's first leaf node,
# then update result
if (result == INT_MAX):
result = level
# if it's not first leaf node,
# then compare the level with
# level of previous leaf node
elif (result != level):
return 0
# check for right child
if (temp.right) :
q.append(temp.right)
# if it's leaf node
if (not temp.right.left and
not temp.right.right):
# if it's first leaf node till now,
# then update the result
if (result == INT_MAX):
result = level
# if it is not the first leaf node,
# then compare the level with level
# of previous leaf node
elif(result != level):
return 0
size -= 1
return 1
# Driver Code
if __name__ == '__main__':
# construct a tree
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.right = newNode(4)
root.right.left = newNode(5)
root.right.right = newNode(6)
result = checkLevelLeafNode(root)
if (result) :
print("All leaf nodes are at same level")
else:
print("Leaf nodes not at same level")
# This code is contributed by SHUBHAMSINGH10
|
linear
|
linear
|
# Python3 program to check if there
# exist an edge whose removal creates
# two trees of same size
# utility function to create a new node
class newNode:
def __init__(self, x):
self.data = x
self.left = self.right = None
# To calculate size of tree
# with given root
def count(root):
if (root == None):
return 0
return (count(root.left) +
count(root.right) + 1)
# This function returns true if there
# is an edge whose removal can divide
# the tree in two halves n is size of tree
def checkRec(root, n):
# Base cases
if (root == None):
return False
# Check for root
if (count(root) == n - count(root)):
return True
# Check for rest of the nodes
return (checkRec(root.left, n) or
checkRec(root.right, n))
# This function mainly uses checkRec()
def check(root):
# Count total nodes in given tree
n = count(root)
# Now recursively check all nodes
return checkRec(root, n)
# Driver code
if __name__ == '__main__':
root = newNode(5)
root.left = newNode(1)
root.right = newNode(6)
root.left.left = newNode(3)
root.right.left = newNode(7)
root.right.right = newNode(4)
if check(root):
print("YES")
else:
print("NO")
# This code is contributed by PranchalK
|
linear
|
quadratic
|
# Python3 program to check if there exist
# an edge whose removal creates two trees
# of same size
class Node:
def __init__(self, x):
self.key = x
self.left = None
self.right = None
# To calculate size of tree with
# given root
def count(node):
if (node == None):
return 0
return (count(node.left) +
count(node.right) + 1)
# This function returns size of tree rooted
# with given root. It also set "res" as true
# if there is an edge whose removal divides
# tree in two halves.n is size of tree
def checkRec(root, n):
global res
# Base case
if (root == None):
return 0
# Compute sizes of left and right children
c = (checkRec(root.left, n) + 1 +
checkRec(root.right, n))
# If required property is true for
# current node set "res" as true
if (c == n - c):
res = True
# Return size
return c
# This function mainly uses checkRec()
def check(root):
# Count total nodes in given tree
n = count(root)
# Initialize result and recursively
# check all nodes
# bool res = false;
checkRec(root, n)
# Driver code
if __name__ == '__main__':
res = False
root = Node(5)
root.left = Node(1)
root.right = Node(6)
root.left.left = Node(3)
root.right.left = Node(7)
root.right.right = Node(4)
check(root)
if res:
print("YES")
else:
print("NO")
# This code is contributed by mohit kumar 29
|
linear
|
linear
|
# Python3 program to check if two Leaf
# Traversal of Two Binary Trees is same or not
# Binary Tree node
class Node:
def __init__(self, x):
self.data = x
self.left = self.right = None
def isLeaf(self):
return (self.left == None and
self.right == None)
# Returns true of leaf traversal of
# two trees is same, else false
def isSame(root1, root2):
# Create empty stacks. These stacks are going
# to be used for iterative traversals.
s1 = []
s2 = []
s1.append(root1)
s2.append(root2)
# Loop until either of two stacks
# is not empty
while (len(s1) != 0 or len(s2) != 0):
# If one of the stacks is empty means other
# stack has extra leaves so return false
if (len(s1) == 0 or len(s2) == 0):
return False
temp1 = s1.pop(-1)
while (temp1 != None and not temp1.isLeaf()):
# append right and left children of temp1.
# Note that right child is inserted
# before left
if (temp1.right != None):
s1.append(temp1. right)
if (temp1.left != None):
s1.append(temp1.left)
temp1 = s1.pop(-1)
# same for tree2
temp2 = s2.pop(-1)
while (temp2 != None and not temp2.isLeaf()):
if (temp2.right != None):
s2.append(temp2.right)
if (temp2.left != None):
s2.append(temp2.left)
temp2 = s2.pop(-1)
# If one is None and other is not,
# then return false
if (temp1 == None and temp2 != None):
return False
if (temp1 != None and temp2 == None):
return False
# If both are not None and data is
# not same return false
if (temp1 != None and temp2 != None):
if (temp1.data != temp2.data):
return False
# If control reaches this point,
# all leaves are matched
return True
# Driver Code
if __name__ == '__main__':
# Let us create trees in above example 1
root1 = Node(1)
root1.left = Node(2)
root1.right = Node(3)
root1.left.left = Node(4)
root1.right.left = Node(6)
root1.right.right = Node(7)
root2 = Node(0)
root2.left = Node(1)
root2.right = Node(5)
root2.left.right = Node(4)
root2.right.left = Node(6)
root2.right.right = Node(7)
if (isSame(root1, root2)):
print("Same")
else:
print("Not Same")
# This code is contributed by pranchalK
|
nlogn
|
linear
|
# Python3 program to find deepest
# left leaf Binary search Tree
# Helper function that allocates a
# new node with the given data and
# None left and right pairs.
class getNode:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# function to check whether a binary
# tree is a full binary tree or not
def isFullBinaryTree( root) :
# if tree is empty
if (not root) :
return True
# queue used for level order
# traversal
q = []
# append 'root' to 'q'
q.append(root)
# traverse all the nodes of the
# binary tree level by level
# until queue is empty
while (not len(q)):
# get the pointer to 'node'
# at front of queue
node = q[0]
q.pop(0)
# if it is a leaf node then continue
if (node.left == None and
node.right == None):
continue
# if either of the child is not None
# and the other one is None, then
# binary tree is not a full binary tee
if (node.left == None or
node.right == None):
return False
# append left and right childs
# of 'node' on to the queue 'q'
q.append(node.left)
q.append(node.right)
# binary tree is a full binary tee
return True
# Driver Code
if __name__ == '__main__':
root = getNode(1)
root.left = getNode(2)
root.right = getNode(3)
root.left.left = getNode(4)
root.left.right = getNode(5)
if (isFullBinaryTree(root)) :
print("Yes" )
else:
print("No")
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)
|
constant
|
linear
|
""" Program to check if a given Binary
Tree is balanced like a Red-Black Tree """
# Helper function that allocates a new
# node with the given data and None
# left and right pointers.
class newNode:
# Construct to create a new node
def __init__(self, key):
self.data = key
self.left = None
self.right = None
# Returns returns tree if the Binary
# tree is balanced like a Red-Black
# tree. This function also sets value
# in maxh and minh (passed by
# reference). maxh and minh are set
# as maximum and minimum heights of root.
def isBalancedUtil(root, maxh, minh) :
# Base case
if (root == None) :
maxh = minh = 0
return True
lmxh=0
# To store max and min
# heights of left subtree
lmnh=0
# To store max and min
# heights of right subtree
rmxh, rmnh=0,0
# Check if left subtree is balanced,
# also set lmxh and lmnh
if (isBalancedUtil(root.left, lmxh, lmnh) == False) :
return False
# Check if right subtree is balanced,
# also set rmxh and rmnh
if (isBalancedUtil(root.right, rmxh, rmnh) == False) :
return False
# Set the max and min heights of
# this node for the parent call
maxh = max(lmxh, rmxh) + 1
minh = min(lmnh, rmnh) + 1
# See if this node is balanced
if (maxh <= 2 * minh) :
return True
return False
# A wrapper over isBalancedUtil()
def isBalanced(root) :
maxh, minh =0,0
return isBalancedUtil(root, maxh, minh)
# Driver Code
if __name__ == '__main__':
root = newNode(10)
root.left = newNode(5)
root.right = newNode(100)
root.right.left = newNode(50)
root.right.right = newNode(150)
root.right.left.left = newNode(40)
if (isBalanced(root)):
print("Balanced")
else:
print("Not Balanced")
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)
|
linear
|
linear
|
MAX = 100
# class for a tree node
class Node:
def __init__(self):
self.key = ' '
self.left = None
self.right = None
# A utility function to create a new BST node
def newNode(item):
temp = Node()
temp.key = item
return temp
# A utility function to store inorder traversal of tree rooted
# with root in an array arr[]. Note that i is passed as reference
def storeInorder(root, i):
if (root == None):
return '$'
res = storeInorder(root.left, i)
res += root.key
res += storeInorder(root.right, i)
return res
# A utility function to store preorder traversal of tree rooted
# with root in an array arr[]. Note that i is passed as reference
def storePreOrder(root, i):
if (root == None):
return '$'
res = root.key
res += storePreOrder(root.left, i)
res += storePreOrder(root.right, i)
return res
# This function returns true if S is a subtree of T, otherwise false
def isSubtree(T, S):
# base cases
if (S == None):
return True
if (T == None):
return False
# Store Inorder traversals of T and S in inT[0..m-1]
# and inS[0..n-1] respectively
m = 0
n = 0
inT = storeInorder(T, m)
inS = storeInorder(S, n)
# If inS[] is not a substring of inT[], return false
res = True
if inS in inT:
res = True
else:
res = False
if(res == False):
return res
# Store Preorder traversals of T and S in preT[0..m-1]
# and preS[0..n-1] respectively
m = 0
n = 0
preT = storePreOrder(T, m)
preS = storePreOrder(S, n)
# If preS[] is not a substring of preT[], return false
# Else return true
if preS in preT:
return True
else:
return False
# Driver program to test above function
T = newNode('a')
T.left = newNode('b')
T.right = newNode('d')
T.left.left = newNode('c')
T.right.right = newNode('e')
S = newNode('a')
S.left = newNode('b')
S.left.left = newNode('c')
S.right = newNode('d')
if (isSubtree(T, S)):
print("Yes: S is a subtree of T")
else:
print("No: S is NOT a subtree of T")
# This code is contributed by rj13to.
|
linear
|
linear
|
# Python3 program to check if two
# trees are mirror of each other
# A binary tree node
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Given two trees, return true
# if they are mirror of each other
def areMirror(a, b):
# Base case : Both empty
if a is None and b is None:
return True
# If only one is empty
if a is None or b is None:
return False
# Both non-empty, compare them
# recursively. Note that in
# recursive calls, we pass left
# of one tree and right of other tree
return (a.data == b.data and
areMirror(a.left, b.right) and
areMirror(a.right , b.left))
# Driver code
root1 = Node(1)
root2 = Node(1)
root1.left = Node(2)
root1.right = Node(3)
root1.left.left = Node(4)
root1.left.right = Node(5)
root2.left = Node(3)
root2.right = Node(2)
root2.right.left = Node(5)
root2.right.right = Node(4)
if areMirror(root1, root2):
print ("Yes")
else:
print ("No")
# This code is contributed by AshishR
|
logn
|
linear
|
# Python3 implementation to check whether
# the two binary trees are mirrors of each
# other or not
# Utility function to create and return
# a new node for a binary tree
class newNode:
def __init__(self, data):
self.data = data
self.left = self.right = None
# function to check whether the two binary
# trees are mirrors of each other or not
def areMirrors(root1, root2):
st1 = []
st2 = []
while (1):
# iterative inorder traversal of 1st tree
# and reverse inorder traversal of 2nd tree
while (root1 and root2):
# if the corresponding nodes in the
# two traversal have different data
# values, then they are not mirrors
# of each other.
if (root1.data != root2.data):
return "No"
st1.append(root1)
st2.append(root2)
root1 = root1.left
root2 = root2.right
# if at any point one root becomes None and
# the other root is not None, then they are
# not mirrors. This condition verifies that
# structures of tree are mirrors of each other.
if (not (root1 == None and root2 == None)):
return "No"
if (not len(st1) == 0 and not len(st2) == 0):
root1 = st1[-1]
root2 = st2[-1]
st1.pop(-1)
st2.pop(-1)
# we have visited the node and its left
# subtree. Now, it's right subtree's turn
root1 = root1.right
# we have visited the node and its right
# subtree. Now, it's left subtree's turn
root2 = root2.left
# both the trees have been
# completely traversed
else:
break
# trees are mirrors of each other
return "Yes"
# Driver Code
if __name__ == '__main__':
# 1st binary tree formation
root1 = newNode(1) # 1
root1.left = newNode(3) # / \
root1.right = newNode(2) # 3 2
root1.right.left = newNode(5)# / \
root1.right.right = newNode(4) # 5 4
# 2nd binary tree formation
root2 = newNode(1) # 1
root2.left = newNode(2) # / \
root2.right = newNode(3) # 2 3
root2.left.left = newNode(4)# / \
root2.left.right = newNode(5)# 4 5
print(areMirrors(root1, root2))
# This code is contributed by pranchalK
|
linear
|
linear
|
# Python3 program to program to check if a
# given Binary Tree is symmetric or not
# Helper function that allocates a new
# node with the given data and None
# left and right pairs.
class newNode:
# Constructor to create a new node
def __init__(self, key):
self.key = key
self.left = None
self.right = None
# function to check if a given
# Binary Tree is symmetric or not
def isSymmetric( root) :
# if tree is empty
if (root == None) :
return True
# If it is a single tree node,
# then it is a symmetric tree.
if(not root.left and not root.right):
return True
q = []
# Add root to queue two times so that
# it can be checked if either one
# child alone is NULL or not.
q.append(root)
q.append(root)
# To store two nodes for checking
# their symmetry.
leftNode = 0
rightNode = 0
while(not len(q)):
# Remove first two nodes to
# check their symmetry.
leftNode = q[0]
q.pop(0)
rightNode = q[0]
q.pop(0)
# if both left and right nodes
# exist, but have different
# values-. inequality, return False
if(leftNode.key != rightNode.key):
return False
# append left child of left subtree
# node and right child of right
# subtree node in queue.
if(leftNode.left and rightNode.right) :
q.append(leftNode.left)
q.append(rightNode.right)
# If only one child is present
# alone and other is NULL, then
# tree is not symmetric.
elif (leftNode.left or rightNode.right) :
return False
# append right child of left subtree
# node and left child of right subtree
# node in queue.
if(leftNode.right and rightNode.left):
q.append(leftNode.right)
q.append(rightNode.left)
# If only one child is present
# alone and other is NULL, then
# tree is not symmetric.
elif(leftNode.right or rightNode.left):
return False
return True
# Driver Code
if __name__ == '__main__':
# Let us construct the Tree
# shown in the above figure
root = newNode(1)
root.left = newNode(2)
root.right = newNode(2)
root.left.left = newNode(3)
root.left.right = newNode(4)
root.right.left = newNode(4)
root.right.right = newNode(3)
if (isSymmetric(root)) :
print("The given tree is Symmetric")
else:
print("The given tree is not Symmetric")
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)
|
logn
|
linear
|
''' A binary tree node has key, pointer to left
child and a pointer to right child '''
class Node:
def __init__(self, key):
self.key=key
self.left = None
self.right = None
# To create a newNode of tree and return pointer
def newNode(key):
temp = Node(key)
return temp
# Takes two parameters - same initially and
# calls recursively
def printMiddleLevelUtil(a, b):
# Base case e
if (a == None or b == None):
return;
# Fast pointer has reached the leaf so print
# value at slow pointer
if ((b.left == None) and (b.right == None)):
print(a.key, end=' ')
return;
# Recursive call
# root.left.left and root.left.right will
# print same value
# root.right.left and root.right.right
# will print same value
# So we use any one of the condition
if (b.left.left):
printMiddleLevelUtil(a.left, b.left.left);
printMiddleLevelUtil(a.right, b.left.left);
else:
printMiddleLevelUtil(a.left, b.left);
printMiddleLevelUtil(a.right, b.left);
# Main printing method that take a Tree as input
def printMiddleLevel(node):
printMiddleLevelUtil(node, node);
# Driver program to test above functions
if __name__=='__main__':
n1 = newNode(1);
n2 = newNode(2);
n3 = newNode(3);
n4 = newNode(4);
n5 = newNode(5);
n6 = newNode(6);
n7 = newNode(7);
n2.left = n4;
n2.right = n5;
n3.left = n6;
n3.right = n7;
n1.left = n2;
n1.right = n3;
printMiddleLevel(n1);
# This code is contributed by rutvik_56
|
logn
|
linear
|
# Python3 program to print the longest
# leaf to leaf path
# Tree node structure used in the program
MAX_PATH_SIZE = 1000
class Node:
def __init__(self, x):
self.data = x
self.left = None
self.right = None
# Prints given root to leafAllpaths
# with underscores
def printPath(size):
global Allpaths
# Find the minimum horizontal distance
# value in current root to leafAllpaths
minimum_Hd = 10**19
p = []
# Find minimum horizontal distance
for it in range(size):
p = Allpaths[it]
minimum_Hd = min(minimum_Hd, p[0])
# Print the root to leafAllpaths with "_"
# that indicate the related position
for it in range(size):
# Current tree node
p = Allpaths[it]
noOfUnderScores = abs(p[0] - minimum_Hd)
# Print underscore
for i in range(noOfUnderScores):
print(end = "_ ")
# Print current key
print(p[1])
print("==============================")
# A utility function print all path from root to leaf
# working of this function is similar to function of
# "Print_vertical_order" : Print paths of binary tree
# in vertical order
# https://www.geeksforgeeks.org/print-binary-tree-vertical-order-set-2/
def printAllPathsUtil(root, HD, order):
# Base case
global Allpaths
if (root == None):
return
# Leaf node
if (root.left == None and root.right == None):
# Add leaf node and then print path
Allpaths[order] = [HD, root.data]
printPath(order + 1)
return
# Store current path information
Allpaths[order] = [HD, root.data]
# Call left sub_tree
printAllPathsUtil(root.left, HD - 1, order + 1)
# Call left sub_tree
printAllPathsUtil(root.right, HD + 1, order + 1)
def printAllPaths(root):
global Allpaths
# Base case
if (root == None):
return
printAllPathsUtil(root, 0, 0)
# Driver code
if __name__ == '__main__':
Allpaths = [ [0, 0] for i in range(MAX_PATH_SIZE)]
root = Node('A')
root.left = Node('B')
root.right = Node('C')
root.left.left = Node('D')
root.left.right = Node('E')
root.right.left = Node('F')
root.right.right = Node('G')
printAllPaths(root)
# This code is contributed by mohit kumar 29
|
logn
|
constant
|
# Recursive Python3 program to print
# odd level nodes
# Utility method to create a node
class newNode:
def __init__(self, data):
self.data = data
self.left = self.right = None
def printOddNodes(root, isOdd = True):
# If empty tree
if (root == None):
return
# If current node is of odd level
if (isOdd):
print(root.data, end = " ")
# Recur for children with isOdd
# switched.
printOddNodes(root.left, not isOdd)
printOddNodes(root.right, not isOdd)
# Driver code
if __name__ == '__main__':
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.left = newNode(4)
root.left.right = newNode(5)
printOddNodes(root)
# This code is contributed by PranchalK
|
linear
|
linear
|
# Iterative Python3 program to print odd
# level nodes
# A Binary Tree Node
# Utility function to create a
# new tree Node
class newNode:
def __init__(self, data):
self.data = data
self.left = self.right = None
# Iterative method to do level order
# traversal line by line
def printOddNodes(root) :
# Base Case
if (root == None):
return
# Create an empty queue for
# level order traversal
q = []
# Enqueue root and initialize
# level as odd
q.append(root)
isOdd = True
while (1) :
# nodeCount (queue size) indicates
# number of nodes at current level.
nodeCount = len(q)
if (nodeCount == 0) :
break
# Dequeue all nodes of current level
# and Enqueue all nodes of next level
while (nodeCount > 0):
node = q[0]
if (isOdd):
print(node.data, end = " ")
q.pop(0)
if (node.left != None) :
q.append(node.left)
if (node.right != None) :
q.append(node.right)
nodeCount -= 1
isOdd = not isOdd
# Driver Code
if __name__ == '__main__':
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.left = newNode(4)
root.left.right = newNode(5)
printOddNodes(root)
# This code is contributed
# by SHUBHAMSINGH10
|
linear
|
linear
|
# Python3 program to find the all
# full nodes in a given binary tree
# Binary Tree Node
""" utility that allocates a newNode
with the given key """
class newNode:
# Construct to create a newNode
def __init__(self, key):
self.data = key
self.left = None
self.right = None
# Traverses given tree in Inorder
# fashion and prints all nodes that
# have both children as non-empty.
def findFullNode(root) :
if (root != None) :
findFullNode(root.left)
if (root.left != None and
root.right != None) :
print(root.data, end = " ")
findFullNode(root.right)
# Driver Code
if __name__ == '__main__':
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.left = newNode(4)
root.right.left = newNode(5)
root.right.right = newNode(6)
root.right.left.right = newNode(7)
root.right.right.right = newNode(8)
root.right.left.right.left = newNode(9)
findFullNode(root)
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)
|
linear
|
linear
|
# Python3 Program to print sum of all
# the elements of a binary tree
# Binary Tree Node
class newNode:
# Utility function to create a new node
def __init__(self, key):
self.key = key
self.left = None
self.right = None
# Function to find sum of all the element
def sumBT(root):
# sum variable to track the sum of
# all variables.
sum = 0
q = []
# Pushing the first level.
q.append(root)
# Pushing elements at each level from
# the tree.
while len(q) > 0:
temp = q.pop(0)
# After popping each element from queue
# add its data to the sum variable.
sum += temp.key
if (temp.left != None):
q.append(temp.left)
if temp.right != None:
q.append(temp.right)
return sum
# Driver Code
if __name__ == '__main__':
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.left = newNode(4)
root.left.right = newNode(5)
root.right.left = newNode(6)
root.right.right = newNode(7)
root.right.left.right = newNode(8)
print("Sum of all elements in the binary tree is: ", sumBT(root))
# This code is contributed by
# Abhijeet Kumar(abhijeet19403)
|
linear
|
linear
|
# Python3 implementation to find the Sum of
# all the parent nodes having child node x
# function to get a new node
class getNode:
def __init__(self, data):
# put in the data
self.data = data
self.left = self.right = None
# function to find the Sum of all the
# parent nodes having child node x
def SumOfParentOfX(root, Sum, x):
# if root == None
if (not root):
return
# if left or right child of root is 'x',
# then add the root's data to 'Sum'
if ((root.left and root.left.data == x) or
(root.right and root.right.data == x)):
Sum[0] += root.data
# recursively find the required parent
# nodes in the left and right subtree
SumOfParentOfX(root.left, Sum, x)
SumOfParentOfX(root.right, Sum, x)
# utility function to find the Sum of all
# the parent nodes having child node x
def SumOfParentOfXUtil(root, x):
Sum = [0]
SumOfParentOfX(root, Sum, x)
# required Sum of parent nodes
return Sum[0]
# Driver Code
if __name__ == '__main__':
# binary tree formation
root = getNode(4) # 4
root.left = getNode(2) # / \
root.right = getNode(5) # 2 5
root.left.left = getNode(7) # / \ / \
root.left.right = getNode(2) # 7 2 2 3
root.right.left = getNode(2)
root.right.right = getNode(3)
x = 2
print("Sum = ", SumOfParentOfXUtil(root, x))
# This code is contributed by PranchalK
|
linear
|
linear
|
# Python3 program to find sum of
# all left leaves
from collections import deque
# A binary tree node
class Node:
def __init__(self, x):
self.key = x
self.left = None
self.right = None
# Return the sum of left leaf nodes
def sumOfLeftLeaves(root):
if (root == None):
return 0
# A queue of pairs to do bfs traversal
# and keep track if the node is a left
# or right child if boolean value
# is true then it is a left child.
q = deque()
q.append([root, 0])
sum = 0
# Do bfs traversal
while (len(q) > 0):
temp = q[0][0]
is_left_child = q[0][1]
q.popleft()
# If temp is a leaf node and
# left child of its parent
if (not temp.left and
not temp.right and
is_left_child):
sum = sum + temp.key
# If it is not leaf then
# push its children nodes
# into queue
if (temp.left):
# Boolean value is true
# here because it is left
# child of its parent
q.append([temp.left, 1])
if (temp.right):
# Boolean value is false
# here because it is
# right child of its parent
q.append([temp.right, 0])
return sum
# Driver Code
if __name__ == '__main__':
root = Node(20)
root.left = Node(9)
root.right = Node(49)
root.right.left = Node(23)
root.right.right = Node(52)
root.right.right.left = Node(50)
root.left.left = Node(5)
root.left.right = Node(12)
root.left.right.right = Node(12)
print("Sum of left leaves is",
sumOfLeftLeaves(root))
# This code is contributed by mohit kumar 29
|
linear
|
linear
|
# Python Code to find sum of nodes on the longest path from root to leaf node
# using level order traversal
# Building a tree node having left and right pointers set to null initially
class Node:
def __init__(self, element):
self.data = element
self.left = None
self.right = None
# To store current Node,it's level and sum in the path
class Element:
def __init__(self, data, level, sum):
self.data = data
self.level = level
self.sum = sum
class Solution:
def longestPathLeaf(self, root):
# maxSumLevel stores maximum sum so far in the path
# maxLevel stores maximum level so far
maxSumLevel = root.data
maxLevel = 0
# queue to implement level order traversal
que = []
# Each element variable stores the current Node, it's level, sum in the path
e = Element(root, 0, root.data)
# push the root element
que.append(e)
# do level order traversal on the tree
while len(que) != 0:
front = que[0]
curr = front.data
del que[0]
# if the level of current front element is greater than the maxLevel so far then update maxSum
if front.level > maxLevel:
maxSumLevel = front.sum
maxLevel = front.level
# if another path competes then update if the sum is greater than the previous path of same height
elif front.level == maxLevel and front.sum > maxSumLevel:
maxSumLevel = front.sum
# push the left element if exists
if curr.left != None:
e = Element(curr.left, front.level+1, curr.left.data+front.sum)
que.append(e)
# push the right element if exists
if curr.right != None:
e = Element(curr.right, front.level+1,
curr.right.data+front.sum)
que.append(e)
# return the answer
return maxSumLevel
# Helper function
if __name__ == '__main__':
s = Solution()
root = Node(4)
root.left = Node(2)
root.right = Node(5)
root.left.left = Node(7)
root.left.right = Node(1)
root.right.left = Node(2)
root.right.right = Node(3)
root.left.right.left = Node(6)
print(s.longestPathLeaf(root))
# This code is contributed by Tapesh(tapeshdua420)
|
linear
|
linear
|
# Python program to find maximumpath sum between two leaves
# of a binary tree
INT_MIN = -2**32
# 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
# Utility function to find maximum sum between any
# two leaves. This function calculates two values:
# 1) Maximum path sum between two leaves which are stored
# in res
# 2) The maximum root to leaf path sum which is returned
# If one side of root is empty, then it returns INT_MIN
def maxPathSumUtil(root, res):
# Base Case
if root is None:
return 0
# if root is leaf node we can return root.data
if not root.left and not root.right:
return root.data
# Find maximumsum in left and right subtree. Also
# find maximum root to leaf sums in left and right
# subtrees ans store them in ls and rs
ls = maxPathSumUtil(root.left, res)
rs = maxPathSumUtil(root.right, res)
# If both left and right children exist
if root.left is not None and root.right is not None:
# update result if needed
res[0] = max(res[0], ls + rs + root.data)
# Return maximum possible value for root being
# on one side
return max(ls, rs) + root.data
# If any of the two children is empty, return
# root sum for root being on one side
if root.left is None:
return rs + root.data
else:
return ls + root.data
# The main function which returns sum of the maximum
# sum path betwee ntwo leaves. THis function mainly
# uses maxPathSumUtil()
def maxPathSum(root):
res = [INT_MIN]
res1 = maxPathSumUtil(root, res)
# we have to check if root.left is None or root.right is None
# for ex:- 10
# / \
# None -5
# this will return INT_MIN but answer is 5 which is res1
if root.left and root.right:
return res[0]
return max(res[0], res1)
# Driver program to test above function
root = Node(-15)
root.left = Node(5)
root.right = Node(6)
root.left.left = Node(-8)
root.left.right = Node(1)
root.left.left.left = Node(2)
root.left.left.right = Node(6)
root.right.left = Node(3)
root.right.right = Node(9)
root.right.right.right = Node(0)
root.right.right.right.left = Node(4)
root.right.right.right.right = Node(-1)
root.right.right.right.right.left = Node(10)
print("Max pathSum of the given binary tree is", maxPathSum(root))
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
|
linear
|
linear
|
# Python3 program to print all paths
# with sum k
# utility function to print contents of
# a vector from index i to it's end
def printVector(v, i):
for j in range(i, len(v)):
print(v[j], end=" ")
print()
# Binary Tree Node
""" utility that allocates a newNode
with the given key """
class newNode:
# Construct to create a newNode
def __init__(self, key):
self.data = key
self.left = None
self.right = None
# This function prints all paths
# that have sum k
def printKPathUtil(root, path, k):
# empty node
if (not root):
return
# add current node to the path
path.append(root.data)
# check if there's any k sum path
# in the left sub-tree.
printKPathUtil(root.left, path, k)
# check if there's any k sum path
# in the right sub-tree.
printKPathUtil(root.right, path, k)
# check if there's any k sum path that
# terminates at this node
# Traverse the entire path as
# there can be negative elements too
f = 0
for j in range(len(path) - 1, -1, -1):
f += path[j]
# If path sum is k, print the path
if (f == k):
printVector(path, j)
# Remove the current element
# from the path
path.pop(-1)
# A wrapper over printKPathUtil()
def printKPath(root, k):
path = []
printKPathUtil(root, path, k)
# Driver Code
if __name__ == '__main__':
root = newNode(1)
root.left = newNode(3)
root.left.left = newNode(2)
root.left.right = newNode(1)
root.left.right.left = newNode(1)
root.right = newNode(-1)
root.right.left = newNode(4)
root.right.left.left = newNode(1)
root.right.left.right = newNode(2)
root.right.right = newNode(5)
root.right.right.right = newNode(2)
k = 5
printKPath(root, k)
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)
|
logn
|
linear
|
# Python3 program to find if there is a
# subtree with given sum
# Binary Tree Node
""" utility that allocates a newNode
with the given key """
class newnode:
# Construct to create a newNode
def __init__(self, key):
self.data = key
self.left = None
self.right = None
# function to check if there exist any
# subtree with given sum
# cur_sum -. sum of current subtree
# from ptr as root
# sum_left -. sum of left subtree from
# ptr as root
# sum_right -. sum of right subtree
# from ptr as root
def sumSubtreeUtil(ptr,cur_sum,sum):
# base condition
if (ptr == None):
cur_sum[0] = 0
return False
# Here first we go to left sub-tree,
# then right subtree then first we
# calculate sum of all nodes of subtree
# having ptr as root and assign it as cur_sum
# cur_sum = sum_left + sum_right + ptr.data
# after that we check if cur_sum == sum
sum_left, sum_right = [0], [0]
x=sumSubtreeUtil(ptr.left, sum_left, sum)
y=sumSubtreeUtil(ptr.right, sum_right, sum)
cur_sum[0] = (sum_left[0] +
sum_right[0] + ptr.data)
return ((x or y)or (cur_sum[0] == sum))
# Wrapper over sumSubtreeUtil()
def sumSubtree(root, sum):
# Initialize sum of subtree with root
cur_sum = [0]
return sumSubtreeUtil(root, cur_sum, sum)
# Driver Code
if __name__ == '__main__':
root = newnode(8)
root.left = newnode(5)
root.right = newnode(4)
root.left.left = newnode(9)
root.left.right = newnode(7)
root.left.right.left = newnode(1)
root.left.right.right = newnode(12)
root.left.right.right.right = newnode(2)
root.right.right = newnode(11)
root.right.right.left = newnode(3)
sum = 22
if (sumSubtree(root, sum)) :
print("Yes" )
else:
print("No")
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)
|
logn
|
linear
|
# Python3 implementation to count subtrees
# that Sum up to a given value x
# class to get a new node
class getNode:
def __init__(self, data):
# put in the data
self.data = data
self.left = self.right = None
# function to count subtrees that
# Sum up to a given value x
def countSubtreesWithSumX(root, count, x):
# if tree is empty
if (not root):
return 0
# Sum of nodes in the left subtree
ls = countSubtreesWithSumX(root.left,
count, x)
# Sum of nodes in the right subtree
rs = countSubtreesWithSumX(root.right,
count, x)
# Sum of nodes in the subtree
# rooted with 'root.data'
Sum = ls + rs + root.data
# if true
if (Sum == x):
count[0] += 1
# return subtree's nodes Sum
return Sum
# utility function to count subtrees
# that Sum up to a given value x
def countSubtreesWithSumXUtil(root, x):
# if tree is empty
if (not root):
return 0
count = [0]
# Sum of nodes in the left subtree
ls = countSubtreesWithSumX(root.left,
count, x)
# Sum of nodes in the right subtree
rs = countSubtreesWithSumX(root.right,
count, x)
# if tree's nodes Sum == x
if ((ls + rs + root.data) == x):
count[0] += 1
# required count of subtrees
return count[0]
# Driver Code
if __name__ == '__main__':
# binary tree creation
# 5
# / \
# -10 3
# / \ / \
# 9 8 -4 7
root = getNode(5)
root.left = getNode(-10)
root.right = getNode(3)
root.left.left = getNode(9)
root.left.right = getNode(8)
root.right.left = getNode(-4)
root.right.right = getNode(7)
x = 7
print("Count =",
countSubtreesWithSumXUtil(root, x))
# This code is contributed by PranchalK
|
logn
|
linear
|
# Python3 program to find if there is
# a subtree with given sum
# Structure of a node of binary tree
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function to get a new node
def getNode(data):
# Allocate space
newNode = Node(data)
return newNode
count = 0
ptr = None
# Utility function to count subtrees that
# sum up to a given value x
def countSubtreesWithSumXUtil(root, x):
global count, ptr
l = 0
r = 0
if (root == None):
return 0
l += countSubtreesWithSumXUtil(root.left, x)
r += countSubtreesWithSumXUtil(root.right, x)
if (l + r + root.data == x):
count += 1
if (ptr != root):
return l + root.data + r
return count
# Driver code
if __name__ == '__main__':
''' binary tree creation
5
/ \
-10 3
/ \ / \
9 8 -4 7
'''
root = getNode(5)
root.left = getNode(-10)
root.right = getNode(3)
root.left.left = getNode(9)
root.left.right = getNode(8)
root.right.left = getNode(-4)
root.right.right = getNode(7)
x = 7
ptr = root
print("Count = " + str(countSubtreesWithSumXUtil(
root, x)))
# This code is contributed by pratham76
|
logn
|
linear
|
# Python3 Implementation to find the maximum Spiral Sum
# Structure of a node in binary tree
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# function to find the maximum sum contiguous subarray
# implementing kadane's algorithm
def maxSum(Arr):
currSum = maxSum = 0
for element in Arr:
currSum = max(currSum + element, element)
maxSum = max(maxSum, currSum)
return maxSum
# function to find maximum spiral sum
def maxSpiralSum(root):
# if tree is empty
if not root:
return 0
# create two stacks to stopre alternative levels
stack_s1 = [] # from levels right to left
stack_s2 = [] # from levels left to right
# store spiral order traversal in Arr
Arr = []
stack_s1.append(root)
# traversing tree in spiral form
# until there are elements in any one
# of the stack
while stack_s1 or stack_s2:
# traverse current level from s1 and
# push node of next level to s2
while stack_s1:
temp = stack_s1.pop()
# append temp-> data to Arr
Arr.append(temp.data)
if temp.right:
stack_s2.append(temp.right)
if temp.left:
stack_s2.append(temp.left)
# traverse current level from s2 and
# push node of next level to s1
while stack_s2:
temp = stack_s2.pop()
# append temp-> data to Arr
Arr.append(temp.data)
if temp.left:
stack_s1.append(temp.left)
if temp.right:
stack_s1.append(temp.right)
return maxSum(Arr)
# Driver code
if __name__ == "__main__":
root = Node(-2)
root.left = Node(-3)
root.right = Node(4)
root.left.left = Node(5)
root.left.right = Node(1)
root.right.left = Node(-2)
root.right.right = Node(-1)
root.left.left.left = Node(-3)
root.right.right.right = Node(2)
print("Maximum Spiral Sum is : ", maxSpiralSum(root))
# This code is contributed by
# Mayank Chaudhary (chaudhary_19)
|
linear
|
linear
|
# Python3 implementation to find the sum
# of leaf node at minimum level
from collections import deque
# Structure of a node in binary tree
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# function to find the sum of leaf nodes
# at minimum level
def sumOfLeafNodesAtLeafLevel(root):
# if tree is empty
if not root:
return 0
# if there is only root node
if not root.left and not root.right:
return root.data
# Queue used for level order traversal
Queue = deque()
sum = f = 0
# push root node in the queue
Queue.append(root)
while not f:
# count no. of nodes present at current level
nc = len(Queue)
# traverse current level nodes
while nc:
top = Queue.popleft()
# if node is leaf node
if not top.left and not top.right:
sum += top.data
# set flag = 1 to signify that
# we have encountered the minimum level
f = 1
else:
# if top's left or right child exist
# push them to Queue
if top.left:
Queue.append(top.left)
if top.right:
Queue.append(top.right)
nc -= 1
# return the sum
return sum
# Driver code
if __name__ == "__main__":
# binary tree creation
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
root.left.right.left = Node(8)
root.right.left.right = Node(9)
print("Sum = ", sumOfLeafNodesAtLeafLevel(root))
# This code is contributed by
# Mayank Chaudhary (chaudhary_19)
|
linear
|
linear
|
# Python3 implementation of above approach
# Structure of a node in binary tree
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
mp = dict()
def solve(root,level):
if(root == None):
return
if root.left == None and root.right == None :
try:
mp[level].append(root.data)
except:
mp[level] = [root.data]
solve(root.left, level+1)
solve(root.right, level+1)
def minLeafSum(root):
solve(root, 0)
sum = 0
for x, i in enumerate(sorted(mp)):
for j in mp[i]:
sum += j
return sum
# Driver code
if __name__ == "__main__":
# binary tree creation
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
print("Sum = ", minLeafSum(root))
# This code is contributed by
# Abhijeet Kumar(abhijeet19403)
|
linear
|
linear
|
# Python3 program to find if
# there is a root to sum path
# 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
"""
Given a tree and a sum, return
true if there is a path from the root
down to a leaf, such that
adding up all the values along the path
equals the given sum.
Strategy: subtract the node
value from the sum when recurring down,
and check to see if the sum
is 0 when you run out of tree.
"""
# s is the sum
def hasPathSum(node, s):
ans = 0
subSum = s - node.data
# If we reach a leaf node and sum becomes 0, then
# return True
if(subSum == 0 and node.left == None and node.right == None):
return True
# Otherwise check both subtrees
if node.left is not None:
ans = ans or hasPathSum(node.left, subSum)
if node.right is not None:
ans = ans or hasPathSum(node.right, subSum)
return ans
# Driver's Code
if __name__ == "__main__":
s = 21
root = Node(10)
root.left = Node(8)
root.right = Node(2)
root.left.right = Node(5)
root.left.left = Node(3)
root.right.left = Node(2)
# Function call
if hasPathSum(root, s):
print("There is a root-to-leaf path with sum %d" % (s))
else:
print("There is no root-to-leaf path with sum %d" % (s))
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
|
logn
|
linear
|
# Python program to find sum of all paths from root to leaves
# 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
# Returns sums of all root to leaf paths. The first parameter is root
# of current subtree, the second paramete"r is value of the number
# formed by nodes from root to this node
def treePathsSumUtil(root, val):
# Base Case
if root is None:
return 0
# Update val
val = (val*10 + root.data)
# If current node is leaf, return the current value of val
if root.left is None and root.right is None:
return val
# Recur sum of values for left and right subtree
return (treePathsSumUtil(root.left, val) +
treePathsSumUtil(root.right, val))
# A wrapper function over treePathSumUtil()
def treePathsSum(root):
# Pass the initial value as 0 as ther is nothing above root
return treePathsSumUtil(root, 0)
# Driver function to test above function
root = Node(6)
root.left = Node(3)
root.right = Node(5)
root.left.left = Node(2)
root.left.right = Node(5)
root.right.right = Node(4)
root.left.right.left = Node(7)
root.left.right.right = Node(4)
print ("Sum of all paths is", treePathsSum(root))
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
|
linear
|
linear
|
# Python program to find sum of all paths from root to leaves
# 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
def treePathsSumUtil(root, currPath, allPath):
# Base Case
if root is None:
return
# append the root data in string format in currPath
currPath.append(str(root.data))
# if we found a leaf node we copy the currPath to allPath
if root.left is None and root.right is None:
allPath.append(currPath.copy())
# traverse in the left subtree
treePathsSumUtil(root.left, currPath, allPath)
# traverse in the right subtree
treePathsSumUtil(root.right, currPath, allPath)
# remove the current element from the path
del currPath[-1]
def treePathsSum(root):
# store all the root to leaf path in allPath
allPath = []
treePathsSumUtil(root, [], allPath)
# store the sum
s = 0
for pathNumber in allPath:
# join the pathNumbers to convert them into the number to calculate sum
k = "".join(pathNumber)
s += int(k)
return s
# Driver function to test above function
root = Node(6)
root.left = Node(3)
root.right = Node(5)
root.left.left = Node(2)
root.left.right = Node(5)
root.right.right = Node(4)
root.left.right.left = Node(7)
root.left.right.right = Node(4)
print("Sum of all paths is", treePathsSum(root))
# this code is contributed by Vivek Maddeshiya
|
linear
|
quadratic
|
"""Find root of tree where children
sum for every node id is given"""
def findRoot(arr, n) :
# Every node appears once as an id, and
# every node except for the root appears
# once in a sum. So if we subtract all
# the sums from all the ids, we're left
# with the root id.
root = 0
for i in range(n):
root += (arr[i][0] - arr[i][1])
return root
# Driver Code
if __name__ == '__main__':
arr = [[1, 5], [2, 0],
[3, 0], [4, 0],
[5, 5], [6, 5]]
n = len(arr)
print(findRoot(arr, n))
# This code is contributed
# by SHUBHAMSINGH10
|
constant
|
linear
|
# Python code to find LCA of given
# two nodes in a tree
maxn = 100005
# the graph
g = [[] for i in range(maxn)]
# level of each node
level = [0] * maxn
e = []
l = []
h = [0] * maxn
# the segment tree
st = [0] * (5 * maxn)
# adding edges to the graph(tree)
def add_edge(u: int, v: int):
g[u].append(v)
g[v].append(u)
# assigning level to nodes
def levelling(src: int):
for i in range(len(g[src])):
des = g[src][i]
if not level[des]:
level[des] = level[src] + 1
leveling(des)
visited = [False] * maxn
# storing the dfs traversal
# in the array e
def dfs(src: int):
e.append(src)
visited[src] = True
for i in range(len(g[src])):
des = g[src][i]
if not visited[des]:
dfs(des)
e.append(src)
# making the array l
def setting_l(n: int):
for i in range(len(e)):
l.append(level[e[i]])
# making the array h
def setting_h(n: int):
for i in range(n + 1):
h[i] = -1
for i in range(len(e)):
# if is already stored
if h[e[i]] == -1:
h[e[i]] = i
# Range minimum query to return the index
# of minimum in the subarray L[qs:qe]
def RMQ(ss: int, se: int, qs: int, qe: int, i: int) -> int:
global st
if ss > se:
return -1
# out of range
if se < qs or qe < ss:
return -1
# in the range
if qs <= ss and se <= qe:
return st[i]
mid = (se + ss) >> 1
stt = RMQ(ss, mid, qs, qe, 2 * i + 1)
en = RMQ(mid + 1, se, qs, qe, 2 * i + 2)
if stt != -1 and en != -1:
if l[stt] < l[en]:
return stt
return en
elif stt != -1:
return stt
elif en != -1:
return en
# constructs the segment tree
def segmentTreeConstruction(ss: int, se: int, i: int):
if ss > se:
return
if ss == se: # leaf
st[i] = ss
return
mid = (ss + se) >> 1
segmentTreeConstruction(ss, mid, 2 * i + 1)
segmentTreeConstruction(mid + 1, se, 2 * i + 2)
if l[st[2 * i + 1]] < l[st[2 * i + 2]]:
st[i] = st[2 * i + 1]
else:
st[i] = st[2 * i + 2]
# Function to get LCA
def LCA(x: int, y: int) -> int:
if h[x] > h[y]:
x, y = y, x
return e[RMQ(0, len(l) - 1, h[x], h[y], 0)]
# Driver Code
if __name__ == "__main__":
# n=number of nodes in the tree
# q=number of queries to answer
n = 15
q = 5
# making the tree
# /*
# 1
# / | \
# 2 3 4
# | \
# 5 6
# / | \
# 8 7 9 (right of 5)
# / | \ | \
# 10 11 12 13 14
# |
# 15
# */
add_edge(1, 2)
add_edge(1, 3)
add_edge(1, 4)
add_edge(3, 5)
add_edge(4, 6)
add_edge(5, 7)
add_edge(5, 8)
add_edge(5, 9)
add_edge(7, 10)
add_edge(7, 11)
add_edge(7, 12)
add_edge(9, 13)
add_edge(9, 14)
add_edge(12, 15)
level[1] = 1
leveling(1)
dfs(1)
setting_l(n)
setting_h(n)
segmentTreeConstruction(0, len(l) - 1, 0)
print(LCA(10, 15))
print(LCA(11, 14))
# This code is contributed by
# sanjeev2552
|
linear
|
nlogn
|
# Python3 program to find maximum difference
# between node and its ancestor
_MIN = -2147483648
_MAX = 2147483648
# Helper function that allocates a new
# node with the given data and None left
# and right pointers.
class newNode:
# Constructor to create a new node
def __init__(self, key):
self.key = key
self.left = None
self.right = None
"""
Recursive function to calculate maximum
ancestor-node difference in binary tree.
It updates value at 'res' to store the
result. The returned value of this function
is minimum value in subtree rooted with 't' """
def maxDiffUtil(t, res):
""" Returning Maximum value if node
is not there (one child case) """
if (t == None):
return _MAX, res
""" If leaf node then just return
node's value """
if (t.left == None and t.right == None):
return t.key, res
""" Recursively calling left and right
subtree for minimum value """
a, res = maxDiffUtil(t.left, res)
b, res = maxDiffUtil(t.right, res)
val = min(a, b)
""" Updating res if (node value - minimum
value from subtree) is bigger than res """
res = max(res, t.key - val)
""" Returning minimum value got so far """
return min(val, t.key), res
""" This function mainly calls maxDiffUtil() """
def maxDiff(root):
# Initialising result with minimum value
res = _MIN
x, res = maxDiffUtil(root, res)
return res
""" Helper function to print inorder
traversal of binary tree """
def inorder(root):
if (root):
inorder(root.left)
prf("%d ", root.key)
inorder(root.right)
# Driver Code
if __name__ == '__main__':
"""
Let us create Binary Tree shown
in above example """
root = newNode(8)
root.left = newNode(3)
root.left.left = newNode(1)
root.left.right = newNode(6)
root.left.right.left = newNode(4)
root.left.right.right = newNode(7)
root.right = newNode(10)
root.right.right = newNode(14)
root.right.right.left = newNode(13)
print(maxDiff(root))
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)
|
linear
|
linear
|
# Python3 program to count
# number of ways to color
# a N node skewed tree with
# k colors such that parent
# and children have different
# colors.
# fast_way is recursive
# method to calculate power
def fastPow(N, K):
if (K == 0):
return 1;
temp = fastPow(N, int(K / 2));
if (K % 2 == 0):
return temp * temp;
else:
return N * temp * temp;
def countWays(N, K):
return K * fastPow(K - 1, N - 1);
# Driver Code
N = 3;
K = 3;
print(countWays(N, K));
# This code is contributed by mits
|
constant
|
logn
|
# Python Program to calculate size of the tree iteratively
# Node Structure
class newNode:
def __init__(self,data):
self.data = data
self.left = self.right = None
# Return size of tree
def sizeoftree(root):
if root == None:
return 0
q = []
q.append(root)
count = 1
while(len(q) != 0):
root = q.pop(0)
if(root.left):
q.append(root.left)
count += 1
if(root.right):
q.append(root.right)
count += 1
return count
# Driver Program
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.left = newNode(4)
root.left.right = newNode(5)
print(sizeoftree(root))
# This is code is contributed by simranjenny84
|
np
|
linear
|
# Program to find height of tree by Iteration Method
# A binary tree node
class Node:
# Constructor to create new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Iterative method to find height of Binary Tree
def treeHeight(root):
# Base Case
if root is None:
return 0
# Create a empty queue for level order traversal
q = []
# Enqueue Root and Initialize Height
q.append(root)
height = 0
while(True):
# nodeCount(queue size) indicates number of nodes
# at current level
nodeCount = len(q)
if nodeCount == 0 :
return height
height += 1
# Dequeue all nodes of current level and Enqueue
# all nodes of next level
while(nodeCount > 0):
node = q[0]
q.pop(0)
if node.left is not None:
q.append(node.left)
if node.right is not None:
q.append(node.right)
nodeCount -= 1
# Driver program to test above function
# Let us create binary tree shown in above diagram
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print ("Height of tree is", treeHeight(root))
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
|
linear
|
linear
|
# Python 3 program to find
# height of complete binary
# tree from total nodes.
import math
def height(N):
return math.ceil(math.log2(N + 1)) - 1
# driver node
N = 6
print(height(N))
# This code is contributed by
# Smitha Dinesh Semwal
|
constant
|
constant
|
# Program to find height of the tree considering
# only even level leaves.
# Helper class that allocates a new node with the
# given data and None left and right pointers.
class newNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def heightOfTreeUtil(root, isEven):
# Base Case
if (not root):
return 0
if (not root.left and not root.right):
if (isEven):
return 1
else:
return 0
# left stores the result of left subtree,
# and right stores the result of right subtree
left = heightOfTreeUtil(root.left, not isEven)
right = heightOfTreeUtil(root.right, not isEven)
#If both left and right returns 0, it means
# there is no valid path till leaf node
if (left == 0 and right == 0):
return 0
return (1 + max(left, right))
def heightOfTree(root):
return heightOfTreeUtil(root, False)
# Driver Code
if __name__ == '__main__':
# Let us create binary tree shown
# in above diagram
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.left = newNode(4)
root.left.right = newNode(5)
root.left.right.left = newNode(6)
print("Height of tree is",
heightOfTree(root))
# This code is contributed by PranchalK
|
linear
|
linear
|
"""
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 height
lh = height(root.left)
rh = height(root.right)
# allowed values for (lh - rh) are 1, -1, 0
if (abs(lh - rh) <= 1) and isBalanced(
root.left) is True and isBalanced(root.right) is True:
return True
# if we reach here means tree is not
# height-balanced tree
return False
# Driver function to test the above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.left.left.left = Node(8)
if isBalanced(root):
print("Tree is balanced")
else:
print("Tree is not balanced")
# This code is contributed by Shweta Singh
|
linear
|
quadratic
|
# Python3 program to find the diameter of binary tree
# 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
# The function Compute the "height" of a tree. Height is the
# number of nodes along the longest path from the root node
# down to the farthest leaf node.
def height(node):
# Base Case : Tree is empty
if node is None:
return 0
# If tree is not empty then height = 1 + max of left
# height and right heights
return 1 + max(height(node.left), height(node.right))
# Function to get the diameter of a binary tree
def diameter(root):
# Base Case when tree is empty
if root is None:
return 0
# Get the height of left and right sub-trees
lheight = height(root.left)
rheight = height(root.right)
# Get the diameter of left and right sub-trees
ldiameter = diameter(root.left)
rdiameter = diameter(root.right)
# Return max of the following tree:
# 1) Diameter of left subtree
# 2) Diameter of right subtree
# 3) Height of left subtree + height of right subtree +1
return max(lheight + rheight + 1, max(ldiameter, rdiameter))
# Driver Code
if __name__ == "__main__":
"""
Constructed binary tree is
1
/ \
2 3
/ \
4 5
"""
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
# Function Call
print(diameter(root))
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
|
linear
|
quadratic
|
# Python3 program to find the diameter of a binary tree
# A binary tree Node
class Node:
# Constructor to create a new Node
def __init__(self, data):
self.data = data
self.left = self.right = None
# utility class to pass height object
class Height:
def __init(self):
self.h = 0
# Optimised recursive function to find diameter
# of binary tree
def diameterOpt(root, height):
# to store height of left and right subtree
lh = Height()
rh = Height()
# base condition- when binary tree is empty
if root is None:
height.h = 0
return 0
# ldiameter --> diameter of left subtree
# rdiameter --> diameter of right subtree
# height of left subtree and right subtree is obtained from lh and rh
# and returned value of function is stored in ldiameter and rdiameter
ldiameter = diameterOpt(root.left, lh)
rdiameter = diameterOpt(root.right, rh)
# height of tree will be max of left subtree
# height and right subtree height plus1
height.h = max(lh.h, rh.h) + 1
# return maximum of the following
# 1)left diameter
# 2)right diameter
# 3)left height + right height + 1
return max(lh.h + rh.h + 1, max(ldiameter, rdiameter))
# function to calculate diameter of binary tree
def diameter(root):
height = Height()
return diameterOpt(root, height)
# Driver Code
if __name__ == "__main__":
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
"""
Constructed binary tree is
1
/ \
2 3
/ \
4 5
"""
print("The diameter of the binary tree is:", end=" ")
# Function Call
print(diameter(root))
# This code is contributed by Shweta Singh(shweta44)
|
linear
|
linear
|
# Simple Python3 program to find diameter
# of a binary tree.
class newNode:
def __init__(self, data):
self.data = data
self.left = self.right = None
# Function to find height of a tree
def height(root, ans):
if (root == None):
return 0
left_height = height(root.left, ans)
right_height = height(root.right, ans)
# update the answer, because diameter
# of a tree is nothing but maximum
# value of (left_height + right_height + 1)
# for each node
ans[0] = max(ans[0], 1 + left_height +
right_height)
return 1 + max(left_height,
right_height)
# Computes the diameter of binary
# tree with given root.
def diameter(root):
if (root == None):
return 0
ans = [-999999999999] # This will store
# the final answer
height_of_tree = height(root, ans)
return ans[0]
# Driver code
if __name__ == '__main__':
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.left = newNode(4)
root.left.right = newNode(5)
print("Diameter is", diameter(root))
# This code is contributed by PranchalK
|
logn
|
linear
|
# Python3 program to find closest
# value in Binary search Tree
_MIN = -2147483648
_MAX = 2147483648
# Helper function that allocates a new
# node with the given data and None
# left and right pointers.
class newnode:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# utility function to return level
# of given node
def getDeepestRightLeafNode(root) :
if (not root):
return None
# create a queue for level
# order traversal
q = []
q.append(root)
result = None
# traverse until the queue is empty
while (len(q)):
temp = q[0]
q.pop(0)
if (temp.left):
q.append(temp.left)
# Since we go level by level, the last
# stored right leaf node is deepest one
if (temp.right):
q.append(temp.right)
if (not temp.right.left and
not temp.right.right):
result = temp.right
return result
# Driver Code
if __name__ == '__main__':
# create a binary tree
root = newnode(1)
root.left = newnode(2)
root.right = newnode(3)
root.left.right = newnode(4)
root.right.left = newnode(5)
root.right.right = newnode(6)
root.right.left.right = newnode(7)
root.right.right.right = newnode(8)
root.right.left.right.left = newnode(9)
root.right.right.right.right = newnode(10)
result = getDeepestRightLeafNode(root)
if result:
print("Deepest Right Leaf Node ::",
result.data)
else:
print("No result, right leaf not found")
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)
|
linear
|
linear
|
"""Python3 program to find value of the
deepest node in a given binary tree"""
# A Binary Tree Node
# Utility function to create a
# new tree node
class newNode:
# Constructor to create a newNode
def __init__(self, data):
self.data= data
self.left = None
self.right = None
self.visited = False
# maxLevel : keeps track of maximum
# level seen so far.
# res : Value of deepest node so far.
# level : Level of root
def find(root, level, maxLevel, res):
if (root != None):
level += 1
find(root.left, level, maxLevel, res)
# Update level and rescue
if (level > maxLevel[0]):
res[0] = root.data
maxLevel[0] = level
find(root.right, level, maxLevel, res)
# Returns value of deepest node
def deepestNode(root) :
# Initialize result and max level
res = [-1]
maxLevel = [-1]
# Updates value "res" and "maxLevel"
# Note that res and maxLen are passed
# by reference.
find(root, 0, maxLevel, res)
return res[0]
# Driver Code
if __name__ == '__main__':
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.left = newNode(4)
root.right.left = newNode(5)
root.right.right = newNode(6)
root.right.left.right = newNode(7)
root.right.right.right = newNode(8)
root.right.left.right.left = newNode(9)
print(deepestNode(root))
# This code is contributed by
# SHUBHAMSINGH10
|
linear
|
linear
|
# A Python3 program to find value of the
# deepest node in a given binary tree by method 3
from collections import deque
class new_Node:
def __init__(self, key):
self.data = key
self.left = self.right = None
def deepestNode(root):
if root == None:
return 0
q = deque()
q.append(root)
node = None
while len(q) != 0:
node = q.popleft()
if node.left is not None:
q.append(node.left)
if node.right is not None:
q.append(node.right)
return node.data
# Driver Code
if __name__ == '__main__':
root = new_Node(1)
root.left = new_Node(2)
root.right = new_Node(3)
root.left.left = new_Node(4)
root.right.left = new_Node(5)
root.right.right = new_Node(6)
root.right.left.right = new_Node(7)
root.right.right.right = new_Node(8)
root.right.left.right.left = new_Node(9)
# Calculating height of tree
levels = deepestNode(root)
# Printing the deepest node
print(levels)
# This code is contributed by Aprajita Chhawi
|
linear
|
linear
|
# Python3 program to find deepest
# left leaf Binary search Tree
_MIN = -2147483648
_MAX = 2147483648
# Helper function that allocates a new
# node with the given data and None
# left and right pointers.
class newnode:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# utility function to return deepest
# left leaf node
def getDeepestLeftLeafNode(root) :
if (not root):
return None
# create a queue for level
# order traversal
q = []
q.append(root)
result = None
# traverse until the queue is empty
while (len(q)):
temp = q[0]
q.pop(0)
if (temp.left):
q.append(temp.left)
if (not temp.left.left and
not temp.left.right):
result = temp.left
# Since we go level by level,
# the last stored right leaf
# node is deepest one
if (temp.right):
q.append(temp.right)
return result
# Driver Code
if __name__ == '__main__':
# create a binary tree
root = newnode(1)
root.left = newnode(2)
root.right = newnode(3)
root.left.Left = newnode(4)
root.right.left = newnode(5)
root.right.right = newnode(6)
root.right.left.right = newnode(7)
root.right.right.right = newnode(8)
root.right.left.right.left = newnode(9)
root.right.right.right.right = newnode(10)
result = getDeepestLeftLeafNode(root)
if result:
print("Deepest Left Leaf Node ::",
result.data)
else:
print("No result, Left leaf not found")
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)
|
linear
|
linear
|
# Python program to find the maximum width of
# binary tree using Level Order Traversal.
# 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 get the maximum width of a binary tree
def getMaxWidth(root):
maxWidth = 0
h = height(root)
# Get width of each level and compare the
# width with maximum width so far
for i in range(1, h+1):
width = getWidth(root, i)
if (width > maxWidth):
maxWidth = width
return maxWidth
# Get width of a given level
def getWidth(root, level):
if root is None:
return 0
if level == 1:
return 1
elif level > 1:
return (getWidth(root.left, level-1) +
getWidth(root.right, level-1))
# UTILITY FUNCTIONS
# Compute the "height" of a tree -- the number of
# nodes along the longest path from the root node
# down to the farthest leaf node.
def height(node):
if node is None:
return 0
else:
# compute the height of each subtree
lHeight = height(node.left)
rHeight = height(node.right)
# use the larger one
return (lHeight+1) if (lHeight > rHeight) else (rHeight+1)
# Driver code
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.right = Node(8)
root.right.right.left = Node(6)
root.right.right.right = Node(7)
"""
Constructed binary tree is:
1
/ \
2 3
/ \ \
4 5 8
/ \
6 7
"""
# Function call
print ("Maximum width is %d" % (getMaxWidth(root)))
# This code is contributed by Naveen Aili
|
constant
|
quadratic
|
# Python program to find the maximum width of binary
# tree using Level Order Traversal with queue.
from _collections import deque
# 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 get the maximum width of a binary tree
def getMaxWidth(root):
# base case
if root is None:
return 0
q = deque()
maxWidth = 0
q.append(root)
while q:
# Get the size of queue when the level order
# traversal for one level finishes
count = len(q)
# Update the maximum node count value
maxWidth = max(count, maxWidth)
while (count is not 0):
count = count-1
temp = q.popleft()
if temp.left is not None:
q.append(temp.left)
if temp.right is not None:
q.append(temp.right)
return maxWidth
# Driver program to test above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.right = Node(8)
root.right.right.left = Node(6)
root.right.right.right = Node(7)
"""
Constructed binary tree is:
1
/ \
2 3
/ \ \
4 5 8
/ \
6 7
"""
# Function call
print ("Maximum width is %d" % (getMaxWidth(root)))
# This code is contributed by Naveen Aili
|
constant
|
linear
|
# Python program to find the maximum width of
# binary tree using Preorder Traversal.
# 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 get the maximum width of a binary tree
def getMaxWidth(root):
h = height(root)
# Create an array that will store count of nodes at each level
count = [0] * h
level = 0
# Fill the count array using preorder traversal
getMaxWidthRecur(root, count, level)
# Return the maximum value from count array
return getMax(count, h)
# A function that fills count array with count of nodes at every
# level of given binary tree
def getMaxWidthRecur(root, count, level):
if root is not None:
count[level] += 1
getMaxWidthRecur(root.left, count, level+1)
getMaxWidthRecur(root.right, count, level+1)
# UTILITY FUNCTIONS
# Compute the "height" of a tree -- the number of
# nodes along the longest path from the root node
# down to the farthest leaf node.
def height(node):
if node is None:
return 0
else:
# compute the height of each subtree
lHeight = height(node.left)
rHeight = height(node.right)
# use the larger one
return (lHeight+1) if (lHeight > rHeight) else (rHeight+1)
# Return the maximum value from count array
def getMax(count, n):
max = count[0]
for i in range(1, n):
if (count[i] > max):
max = count[i]
return max
# Driver program to test above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.right = Node(8)
root.right.right.left = Node(6)
root.right.right.right = Node(7)
"""
Constructed binary tree is:
1
/ \
2 3
/ \ \
4 5 8
/ \
6 7
"""
print ("Maximum width is %d" % (getMaxWidth(root)))
# This code is contributed by Naveen Aili
|
logn
|
linear
|
# Python code to find vertical
# width of a binary tree
class Node:
def __init__(self, data):
self.data = data
self.left = self.right = None
# Function to fill hd in set.
def fillSet(root, s, hd):
if (not root):
return
fillSet(root.left, s, hd - 1)
s.add(hd)
fillSet(root.right, s, hd + 1)
def verticalWidth(root):
s = set()
# Third parameter is horizontal
# distance
fillSet(root, s, 0)
return len(s)
if __name__ == '__main__':
# Creating the above tree
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
root.right.left.right = Node(8)
root.right.right.right = Node(9)
print(verticalWidth(root))
# This code is contributed by PranchalK
|
linear
|
linear
|
# Python program to determine whether
# vertical level l of binary tree
# is sorted or not.
from collections import deque
from sys import maxsize
INT_MIN = -maxsize
# Structure of a tree node.
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
# Helper function to determine if
# vertical level l of given binary
# tree is sorted or not.
def isSorted(root: Node, level: int) -> bool:
# If root is null, then the answer is an
# empty subset and an empty subset is
# always considered to be sorted.
if root is None:
return True
# Variable to store previous
# value in vertical level l.
prevVal = INT_MIN
# Variable to store current level
# while traversing tree vertically.
currLevel = 0
# Variable to store current node
# while traversing tree vertically.
currNode = Node(0)
# Declare queue to do vertical order
# traversal. A pair is used as element
# of queue. The first element in pair
# represents the node and the second
# element represents vertical level
# of that node.
q = deque()
# Insert root in queue. Vertical level
# of root is 0.
q.append((root, 0))
# Do vertical order traversal until
# all the nodes are not visited.
while q:
currNode = q[0][0]
currLevel = q[0][1]
q.popleft()
# Check if level of node extracted from
# queue is required level or not. If it
# is the required level then check if
# previous value in that level is less
# than or equal to value of node.
if currLevel == level:
if prevVal <= currNode.key:
prevVal = currNode.key
else:
return False
# If left child is not NULL then push it
# in queue with level reduced by 1.
if currNode.left:
q.append((currNode.left, currLevel - 1))
# If right child is not NULL then push it
# in queue with level increased by 1.
if currNode.right:
q.append((currNode.right, currLevel + 1))
# If the level asked is not present in the
# given binary tree, that means that level
# will contain an empty subset. Therefore answer
# will be true.
return True
# Driver Code
if __name__ == "__main__":
# /*
# 1
# / \
# 2 5
# / \
# 7 4
# /
# 6
# */
root = Node(1)
root.left = Node(2)
root.right = Node(5)
root.left.left = Node(7)
root.left.right = Node(4)
root.left.right.left = Node(6)
level = -1
if isSorted(root, level):
print("Yes")
else:
print("No")
# This code is contributed by
# sanjeev2552
|
linear
|
linear
|
# Python3 program to determine whether
# binary tree is level sorted or not.
from queue import Queue
# Function to create new tree node.
class newNode:
def __init__(self, key):
self.key = key
self.left = self.right = None
# Function to determine if given binary
# tree is level sorted or not.
def isSorted(root):
# to store maximum value of previous
# level.
prevMax = -999999999999
# to store minimum value of current
# level.
minval = None
# to store maximum value of current
# level.
maxval = None
# to store number of nodes in current
# level.
levelSize = None
# queue to perform level order traversal.
q = Queue()
q.put(root)
while (not q.empty()):
# find number of nodes in current
# level.
levelSize = q.qsize()
minval = 999999999999
maxval = -999999999999
# traverse current level and find
# minimum and maximum value of
# this level.
while (levelSize > 0):
root = q.queue[0]
q.get()
levelSize -= 1
minval = min(minval, root.key)
maxval = max(maxval, root.key)
if (root.left):
q.put(root.left)
if (root.right):
q.put(root.right)
# if minimum value of this level
# is not greater than maximum
# value of previous level then
# given tree is not level sorted.
if (minval <= prevMax):
return 0
# maximum value of this level is
# previous maximum value for
# next level.
prevMax = maxval
return 1
# Driver Code
if __name__ == '__main__':
#
# 1
# /
# 4
# \
# 6
# / \
# 8 9
# / \
# 12 10
root = newNode(1)
root.left = newNode(4)
root.left.right = newNode(6)
root.left.right.left = newNode(8)
root.left.right.right = newNode(9)
root.left.right.left.left = newNode(12)
root.left.right.right.right = newNode(10)
if (isSorted(root)):
print("Sorted")
else:
print("Not sorted")
# This code is contributed by PranchalK
|
linear
|
linear
|
# Python program to count leaf nodes in Binary Tree
# 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 get the count of leaf nodes in binary tree
def getLeafCount(node):
if node is None:
return 0
if(node.left is None and node.right is None):
return 1
else:
return getLeafCount(node.left) + getLeafCount(node.right)
# Driver program to test above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print ("Leaf count of the tree is %d" %(getLeafCount(root)))
#This code is contributed by Nikhil Kumar Singh(nickzuck_007)
|
logn
|
linear
|
# Python3 program to count total number
# of non-leaf nodes in a binary tree
# class that allocates a new node with the
#given data and None left and right pointers.
class newNode:
def __init__(self,data):
self.data = data
self.left = self.right = None
# Computes the number of non-leaf
# nodes in a tree.
def countNonleaf(root):
# Base cases.
if (root == None or (root.left == None and
root.right == None)):
return 0
# If root is Not None and its one of
# its child is also not None
return (1 + countNonleaf(root.left) +
countNonleaf(root.right))
# Driver Code
if __name__ == '__main__':
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.left = newNode(4)
root.left.right = newNode(5)
print(countNonleaf(root))
# This code is contributed by PranchalK
|
logn
|
linear
|
# Python program to count
# half nodes in a Binary Tree
# using iterative approach
# A node structure
class Node:
# A utility function to create a new node
def __init__(self ,key):
self.data = key
self.left = None
self.right = None
# Iterative Method to count half nodes of binary tree
def gethalfCount(root):
# Base Case
if root is None:
return 0
# Create an empty queue for level order traversal
queue = []
# Enqueue Root and initialize count
queue.append(root)
count = 0 #initialize count for half nodes
while(len(queue) > 0):
node = queue.pop(0)
# if it is half node then increment count
if node.left is not None and node.right is None or node.left is None and node.right is not None:
count = count+1
#Enqueue left child
if node.left is not None:
queue.append(node.left)
# Enqueue right child
if node.right is not None:
queue.append(node.right)
return count
#Driver Program to test above function
root = Node(2)
root.left = Node(7)
root.right = Node(5)
root.left.right = Node(6)
root.left.right.left = Node(1)
root.left.right.right = Node(11)
root.right.right = Node(9)
root.right.right.left = Node(4)
print "%d" %(gethalfCount(root))
|
linear
|
linear
|
# Python program to count half nodes in a binary tree
# A node structure
class newNode:
def __init__(self, data):
self.data = data
self.left = self.right = None
# Function to get the count of half Nodes in a binary tree
def gethalfCount(root):
if root == None:
return 0
res = 0
if(root.left == None and root.right != None) or \
(root.left != None and root.right == None):
res += 1
res += (gethalfCount(root.left) + \
gethalfCount(root.right))
return res
# Driver program
''' 2
/ \
7 5
\ \
6 9
/ \ /
1 11 4
Let us create Binary Tree shown in
above example '''
root = newNode(2)
root.left = newNode(7)
root.right = newNode(5)
root.left.right = newNode(6)
root.left.right.left = newNode(1)
root.left.right.right = newNode(11)
root.right.right = newNode(9)
root.right.right.left = newNode(4)
print(gethalfCount(root))
# This code is contributed by simranjenny84
|
linear
|
linear
|
# Python program to count
# full nodes in a Binary Tree
# using iterative approach
# A node structure
class Node:
# A utility function to create a new node
def __init__(self ,key):
self.data = key
self.left = None
self.right = None
# Iterative Method to count full nodes of binary tree
def getfullCount(root):
# Base Case
if root is None:
return 0
# Create an empty queue for level order traversal
queue = []
# Enqueue Root and initialize count
queue.append(root)
count = 0 #initialize count for full nodes
while(len(queue) > 0):
node = queue.pop(0)
# if it is full node then increment count
if node.left is not None and node.right is not None:
count = count+1
# Enqueue left child
if node.left is not None:
queue.append(node.left)
# Enqueue right child
if node.right is not None:
queue.append(node.right)
return count
# Driver Program to test above function
root = Node(2)
root.left = Node(7)
root.right = Node(5)
root.left.right = Node(6)
root.left.right.left = Node(1)
root.left.right.right = Node(11)
root.right.right = Node(9)
root.right.right.left = Node(4)
print(getfullCount(root))
|
linear
|
linear
|
# Python program to count full
# nodes in a Binary Tree
class newNode():
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function to get the count of
# full Nodes in a binary tree
def getfullCount(root):
if (root == None):
return 0
res = 0
if (root.left and root.right):
res += 1
res += (getfullCount(root.left) +
getfullCount(root.right))
return res
# Driver code
if __name__ == '__main__':
""" 2
/ \
7 5
\ \
6 9
/ \ /
1 11 4
Let us create Binary Tree as shown
"""
root = newNode(2)
root.left = newNode(7)
root.right = newNode(5)
root.left.right = newNode(6)
root.left.right.left = newNode(1)
root.left.right.right = newNode(11)
root.right.right = newNode(9)
root.right.right.left = newNode(4)
print(getfullCount(root))
# This code is contributed by SHUBHAMSINGH10
|
linear
|
linear
|
#! /usr/bin/env python3
# connect nodes at same level using level order traversal
import sys
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
self.nextRight = None
def __str__(self):
return '{}'.format(self.data)
def printLevelByLevel(root):
# print level by level
if root:
node = root
while node:
print('{}'.format(node.data), end=' ')
node = node.nextRight
print()
if root.left:
printLevelByLevel(root.left)
else:
printLevelByLevel(root.right)
def inorder(root):
if root:
inorder(root.left)
print(root.data, end=' ')
inorder(root.right)
def connect(root):
# set nextRight of all nodes of a tree
queue = []
queue.append(root)
# null marker to represent end of current level
queue.append(None)
# do level order of tree using None markers
while queue:
p = queue.pop(0)
if p:
# next element in queue represents
# next node at current level
p.nextRight = queue[0]
# pus left and right children of current node
if p.left:
queue.append(p.left)
if p.right:
queue.append(p.right)
else if queue:
queue.append(None)
def main():
"""Driver program to test above functions.
Constructed binary tree is
10
/ \
8 2
/ \
3 90
"""
root = Node(10)
root.left = Node(8)
root.right = Node(2)
root.left.left = Node(3)
root.right.right = Node(90)
# Populates nextRight pointer in all nodes
connect(root)
# Let us check the values of nextRight pointers
print("Following are populated nextRight pointers in \n"
"the tree (-1 is printed if there is no nextRight) \n")
if(root.nextRight != None):
print("nextRight of %d is %d \n" %(root.data,root.nextRight.data))
else:
print("nextRight of %d is %d \n" %(root.data,-1))
if(root.left.nextRight != None):
print("nextRight of %d is %d \n" %(root.left.data,root.left.nextRight.data))
else:
print("nextRight of %d is %d \n" %(root.left.data,-1))
if(root.right.nextRight != None):
print("nextRight of %d is %d \n" %(root.right.data,root.right.nextRight.data))
else:
print("nextRight of %d is %d \n" %(root.right.data,-1))
if(root.left.left.nextRight != None):
print("nextRight of %d is %d \n" %(root.left.left.data,root.left.left.nextRight.data))
else:
print("nextRight of %d is %d \n" %(root.left.left.data,-1))
if(root.right.right.nextRight != None):
print("nextRight of %d is %d \n" %(root.right.right.data,root.right.right.nextRight.data))
else:
print("nextRight of %d is %d \n" %(root.right.right.data,-1))
print()
if __name__ == "__main__":
main()
# This code is contributed by Ram Basnet
|
linear
|
linear
|
# Iterative program to connect all the adjacent nodes at the same level in a binary tree
class newnode:
def __init__(self, data):
self.data = data
self.left = self.right = self.nextRight = None
# setting right pointer to next right node
# 10 ----------> NULL
# / \
# 8 --->2 --------> NULL
# /
# 3 ----------------> NULL
def connect(root):
# Base condition
if root is None:
return
# Create an empty queue like level order traversal
queue = []
queue.append(root)
while len(queue) != 0:
# size indicates no. of nodes at current level
size = len(queue)
# for keeping track of previous node
prev = newnode(None)
for i in range(size):
temp = queue.pop(0)
if temp.left:
queue.append(temp.left)
if temp.right:
queue.append(temp.right)
if prev != None:
prev.nextRight = temp
prev = temp
prev.nextRight = None
# Driver Code
if __name__ == '__main__':
# Constructed binary tree is
# 10
# / \
# 8 2
# /
# 3
root = newnode(10)
root.left = newnode(8)
root.right = newnode(2)
root.left.left = newnode(3)
# Populates nextRight pointer in all nodes
connect(root)
# Let us check the values of nextRight pointers
print("Following are populated nextRight",
"pointers in the tree (-1 is printed",
"if there is no nextRight)")
print("nextRight of", root.data, "is ", end="")
if root.nextRight:
print(root.nextRight.data)
else:
print(-1)
print("nextRight of", root.left.data, "is ", end="")
if root.left.nextRight:
print(root.left.nextRight.data)
else:
print(-1)
print("nextRight of", root.right.data, "is ", end="")
if root.right.nextRight:
print(root.right.nextRight.data)
else:
print(-1)
print("nextRight of", root.left.left.data, "is ", end="")
if root.left.left.nextRight:
print(root.left.left.nextRight.data)
else:
print(-1)
# This code is contributed by Vivek Maddeshiya
|
linear
|
linear
|
# Python3 implementation to find the
# level having Maximum number of Nodes
# Importing Queue
from queue import Queue
# Helper class that allocates a new
# node with the given data and None
# left and right pointers.
class newNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# function to find the level
# having Maximum number of Nodes
def maxNodeLevel(root):
if (root == None):
return -1
q = Queue()
q.put(root)
# Current level
level = 0
# Maximum Nodes at same level
Max = -999999999999
# Level having Maximum Nodes
level_no = 0
while (1):
# Count Nodes in a level
NodeCount = q.qsize()
if (NodeCount == 0):
break
# If it is Maximum till now
# Update level_no to current level
if (NodeCount > Max):
Max = NodeCount
level_no = level
# Pop complete current level
while (NodeCount > 0):
Node = q.queue[0]
q.get()
if (Node.left != None):
q.put(Node.left)
if (Node.right != None):
q.put(Node.right)
NodeCount -= 1
# Increment for next level
level += 1
return level_no
# Driver Code
if __name__ == '__main__':
# binary tree formation
root = newNode(2) # 2
root.left = newNode(1) # / \
root.right = newNode(3) # 1 3
root.left.left = newNode(4) # / \ \
root.left.right = newNode(6) # 4 6 8
root.right.right = newNode(8) # /
root.left.right.left = newNode(5)# 5
print("Level having Maximum number of Nodes : ",
maxNodeLevel(root))
# This code is contributed by Pranchalk
|
linear
|
linear
|
# Python program to print largest value
# on each level of binary tree
INT_MIN = -2147483648
# Helper function that allocates a new
# node with the given data and None left
# and right pointers.
class newNode:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# function to find largest values
def largestValueInEachLevel(root):
if (not root):
return
q = []
nc = 10
max = 0
q.append(root)
while (1):
# node count for the current level
nc = len(q)
# if true then all the nodes of
# the tree have been traversed
if (nc == 0):
break
# maximum element for the current
# level
max = INT_MIN
while (nc):
# get the front element from 'q'
front = q[0]
# remove front element from 'q'
q = q[1:]
# if true, then update 'max'
if (max < front.data):
max = front.data
# if left child exists
if (front.left):
q.append(front.left)
# if right child exists
if (front.right != None):
q.append(front.right)
nc -= 1
# print maximum element of
# current level
print(max, end=" ")
# Driver Code
if __name__ == '__main__':
""" Let us construct the following Tree
4
/ \
9 2
/ \ \
3 5 7 """
root = newNode(4)
root.left = newNode(9)
root.right = newNode(2)
root.left.left = newNode(3)
root.left.right = newNode(5)
root.right.right = newNode(7)
# Function call
largestValueInEachLevel(root)
# This code is contributed
# Shubham Singh(SHUBHAMSINGH10)
|
constant
|
linear
|
# Python3 program to find closest
# value in Binary search Tree
_MIN = -2147483648
_MAX = 2147483648
# Helper function that allocates a new
# node with the given data and None
# left and right pointers.
class getnode:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# utility function to return level
# of given node
def getlevel(root, data):
q = []
level = 1
q.append(root)
# extra None is appended to keep track
# of all the nodes to be appended
# before level is incremented by 1
q.append(None)
while (len(q)):
temp = q[0]
q.pop(0)
if (temp == None) :
if len(q) == 0:
return 0
if (q[0] != None):
q.append(None)
level += 1
else :
if (temp.data == data) :
return level
if (temp.left):
q.append(temp.left)
if (temp.right) :
q.append(temp.right)
return 0
# Driver Code
if __name__ == '__main__':
# create a binary tree
root = getnode(20)
root.left = getnode(10)
root.right = getnode(30)
root.left.left = getnode(5)
root.left.right = getnode(15)
root.left.right.left = getnode(12)
root.right.left = getnode(25)
root.right.right = getnode(40)
# return level of node
level = getlevel(root, 30)
if level != 0:
print("level of node 30 is", level)
else:
print("node 30 not found")
level = getlevel(root, 12)
if level != 0:
print("level of node 12 is", level)
else:
print("node 12 not found")
level = getlevel(root, 25)
if level != 0:
print("level of node 25 is", level)
else:
print("node 25 not found")
level = getlevel(root, 27)
if level != 0:
print("level of node 27 is", level)
else:
print("node 27 not found")
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)
|
linear
|
linear
|
# Python program to remove all half nodes
# A binary tree node
class Node:
# Constructor for creating a new node
def __init__(self , data):
self.data = data
self.left = None
self.right = None
# For inorder traversal
def printInorder(root):
if root is not None:
printInorder(root.left)
print (root.data,end=" ")
printInorder(root.right)
# Removes all nodes with only one child and returns
# new root(note that root may change)
def RemoveHalfNodes(root):
if root is None:
return None
# Recur to left tree
root.left = RemoveHalfNodes(root.left)
# Recur to right tree
root.right = RemoveHalfNodes(root.right)
# if both left and right child is None
# the node is not a Half node
if root.left is None and root.right is None:
return root
# If current nodes is a half node with left child
# None then it's right child is returned and
# replaces it in the given tree
if root.left is None:
new_root = root.right
temp = root
root = None
del(temp)
return new_root
if root.right is None:
new_root = root.left
temp = root
root = None
del(temp)
return new_root
return root
# Driver Program
root = Node(2)
root.left = Node(7)
root.right = Node(5)
root.left.right = Node(6)
root.left.right.left = Node(1)
root.left.right.right = Node(11)
root.right.right = Node(9)
root.right.right.left = Node(4)
print ("Inorder traversal of given tree")
printInorder(root)
NewRoot = RemoveHalfNodes(root)
print ("\nInorder traversal of the modified tree")
printInorder(NewRoot)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
|
constant
|
linear
|
# Python3 program to find the length of longest
# path with same values in a binary tree.
# Helper function that allocates a
# new node with the given data and
# None left and right pointers.
class newNode:
def __init__(self, data):
self.val = data
self.left = self.right = None
# Function to print the longest path
# of same values
def length(node, ans):
if (not node):
return 0
# Recursive calls to check for subtrees
left = length(node.left, ans)
right = length(node.right, ans)
# Variables to store maximum lengths
# in two directions
Leftmax = 0
Rightmax = 0
# If curr node and it's left child has same value
if (node.left and node.left.val == node.val):
Leftmax += left + 1
# If curr node and it's right child has same value
if (node.right and node.right.val == node.val):
Rightmax += right + 1
ans[0] = max(ans[0], Leftmax + Rightmax)
return max(Leftmax, Rightmax)
# Driver function to find length of
# longest same value path
def longestSameValuePath(root):
ans = [0]
length(root, ans)
return ans[0]
# Driver code
if __name__ == '__main__':
# Let us construct a Binary Tree
# 4
# / \
# 4 4
# / \ \
# 4 9 5
root = None
root = newNode(4)
root.left = newNode(4)
root.right = newNode(4)
root.left.left = newNode(4)
root.left.right = newNode(9)
root.right.right = newNode(5)
print(longestSameValuePath(root))
# This code is contributed by PranchalK
|
logn
|
linear
|
# Python3 program to find distance of
# a given node from root.
# A class to create a new Binary
# Tree Node
class newNode:
def __init__(self, item):
self.data = item
self.left = self.right = None
# Returns -1 if x doesn't exist in tree.
# Else returns distance of x from root
def findDistance(root, x):
# Base case
if (root == None):
return -1
# Initialize distance
dist = -1
# Check if x is present at root or
# in left subtree or right subtree.
if (root.data == x):
return dist + 1
else:
dist = findDistance(root.left, x)
if dist >= 0:
return dist + 1
else:
dist = findDistance(root.right, x)
if dist >= 0:
return dist + 1
return dist
# Driver Code
if __name__ == '__main__':
root = newNode(5)
root.left = newNode(10)
root.right = newNode(15)
root.left.left = newNode(20)
root.left.right = newNode(25)
root.left.right.right = newNode(45)
root.right.left = newNode(30)
root.right.right = newNode(35)
print(findDistance(root, 45))
# This code is contributed by PranchalK
|
constant
|
linear
|
# Python3 program to print right sibling
# of a node
# A class to create a new Binary
# Tree Node
class newNode:
def __init__(self, item, parent):
self.data = item
self.left = self.right = None
self.parent = parent
# Method to find right sibling
def findRightSibling(node, level):
if (node == None or node.parent == None):
return None
# GET Parent pointer whose right child is not
# a parent or itself of this node. There might
# be case when parent has no right child, but,
# current node is left child of the parent
# (second condition is for that).
while (node.parent.right == node or
(node.parent.right == None and
node.parent.left == node)):
if (node.parent == None):
return None
node = node.parent
level -= 1
# Move to the required child, where
# right sibling can be present
node = node.parent.right
# find right sibling in the given subtree
# (from current node), when level will be 0
while (level < 0):
# Iterate through subtree
if (node.left != None):
node = node.left
else if (node.right != None):
node = node.right
else:
# if no child are there, we cannot
# have right sibling in this path
break
level += 1
if (level == 0):
return node
# This is the case when we reach 9 node
# in the tree, where we need to again
# recursively find the right sibling
return findRightSibling(node, level)
# Driver Code
if __name__ == '__main__':
root = newNode(1, None)
root.left = newNode(2, root)
root.right = newNode(3, root)
root.left.left = newNode(4, root.left)
root.left.right = newNode(6, root.left)
root.left.left.left = newNode(7, root.left.left)
root.left.left.left.left = newNode(10, root.left.left.left)
root.left.right.right = newNode(9, root.left.right)
root.right.right = newNode(5, root.right)
root.right.right.right = newNode(8, root.right.right)
root.right.right.right.right = newNode(12, root.right.right.right)
# passing 10
res = findRightSibling(root.left.left.left.left, 0)
if (res == None):
print("No right sibling")
else:
print(res.data)
# This code is contributed by PranchalK
|
constant
|
linear
|
# Python3 program to find next right of a
# given key using preorder traversal
# class to create a new tree node
class newNode:
def __init__(self, key):
self.key = key
self.left = self.right = None
# Function to find next node for given node
# in same level in a binary tree by using
# pre-order traversal
def nextRightNode(root, k, level, value_level):
# return None if tree is empty
if (root == None):
return None
# if desired node is found, set
# value_level to current level
if (root.key == k):
value_level[0] = level
return None
# if value_level is already set, then
# current node is the next right node
elif (value_level[0]):
if (level == value_level[0]):
return root
# recurse for left subtree by increasing
# level by 1
leftNode = nextRightNode(root.left, k,
level + 1, value_level)
# if node is found in left subtree,
# return it
if (leftNode):
return leftNode
# recurse for right subtree by
# increasing level by 1
return nextRightNode(root.right, k,
level + 1, value_level)
# Function to find next node of given node
# in the same level in given binary tree
def nextRightNodeUtil(root, k):
value_level = [0]
return nextRightNode(root, k, 1, value_level)
# A utility function to test above functions
def test(root, k):
nr = nextRightNodeUtil(root, k)
if (nr != None):
print("Next Right of", k, "is", nr.key)
else:
print("No next right node found for", k)
# Driver Code
if __name__ == '__main__':
# Let us create binary tree given in the
# above example
root = newNode(10)
root.left = newNode(2)
root.right = newNode(6)
root.right.right = newNode(5)
root.left.left = newNode(8)
root.left.right = newNode(4)
test(root, 10)
test(root, 2)
test(root, 6)
test(root, 5)
test(root, 8)
test(root, 4)
# This code is contributed by PranchalK
|
constant
|
linear
|
# Python3 Program to find Tilt of
# Binary Tree
# class that allocates a new node
# with the given data and
# None left and right pointers.
class newNode:
def __init__(self, data):
self.val = data
self.left = self.right = None
# Recursive function to calculate
# Tilt of whole tree
def traverse(root, tilt):
if (not root):
return 0
# Compute tilts of left and right subtrees
# and find sums of left and right subtrees
left = traverse(root.left, tilt)
right = traverse(root.right, tilt)
# Add current tilt to overall
tilt[0] += abs(left - right)
# Returns sum of nodes under
# current tree
return left + right + root.val
# Driver function to print Tilt
# of whole tree
def Tilt(root):
tilt = [0]
traverse(root, tilt)
return tilt[0]
# Driver code
if __name__ == '__main__':
# Let us construct a Binary Tree
# 4
# / \
# 2 9
# / \ \
# 3 5 7
root = None
root = newNode(4)
root.left = newNode(2)
root.right = newNode(9)
root.left.left = newNode(3)
root.left.right = newNode(8)
root.right.right = newNode(7)
print("The Tilt of whole tree is",
Tilt(root))
# This code is contributed by PranchalK
|
linear
|
linear
|
# Python3 program to find averages of
# all levels in a binary tree.
# Helper function that allocates a
# new node with the given data and
# None left and right pointers.
class newNode:
def __init__(self, data):
self.data = data
self.left = self.right = None
def inorder(node, m):
if (not node):
return ""
Str = "("
Str += inorder(node.left, m)
Str += str(node.data)
Str += inorder(node.right, m)
Str += ")"
# Subtree already present (Note that
# we use unordered_map instead of
# unordered_set because we want to print
# multiple duplicates only once, consider
# example of 4 in above subtree, it
# should be printed only once.
if (Str in m and m[Str] == 1):
print(node.data, end = " ")
if Str in m:
m[Str] += 1
else:
m[Str] = 1
return Str
# Wrapper over inorder()
def printAllDups(root):
m = {}
inorder(root, m)
# Driver code
if __name__ == '__main__':
root = None
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.left = newNode(4)
root.right.left = newNode(2)
root.right.left.left = newNode(4)
root.right.right = newNode(4)
printAllDups(root)
# This code is contributed by PranchalK
|
quadratic
|
quadratic
|
# Python3 program to find largest three
# elements in a binary tree.
# Helper function that allocates a new
# Node with the given data and None
# left and right pointers.
class newNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# function to find three largest element
def threelargest(root, first, second, third):
if (root == None):
return
# if data is greater than first large
# number update the top three list
if (root.data > first[0]):
third[0] = second[0]
second[0] = first[0]
first[0] = root.data
# if data is greater than second large
# number and not equal to first update
# the bottom two list
elif (root.data > second[0] and
root.data != first[0]):
third[0] = second[0]
second[0] = root.data
# if data is greater than third large
# number and not equal to first & second
# update the third highest list
elif (root.data > third[0] and
root.data != first[0] and
root.data != second[0]):
third[0] = root.data
threelargest(root.left, first,
second, third)
threelargest(root.right, first,
second, third)
# Driver Code
if __name__ == '__main__':
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.left = newNode(4)
root.left.right = newNode(5)
root.right.left = newNode(4)
root.right.right = newNode(5)
first = [0]
second = [0]
third = [0]
threelargest(root, first, second, third)
print("three largest elements are",
first[0], second[0], third[0])
# This code is contributed by PranchalK
|
constant
|
linear
|
# Python3 program to print DFS traversal
# from a given graph
from collections import defaultdict
# This class represents a directed graph using
# adjacency list representation
class Graph:
# Constructor
def __init__(self):
# default dictionary to store graph
self.graph = defaultdict(list)
# function to add an edge to graph
def addEdge(self, u, v):
self.graph[u].append(v)
# A function used by DFS
def DFSUtil(self, v, visited):
# Mark the current node as visited
# and print it
visited.add(v)
print(v, end=' ')
# Recur for all the vertices
# adjacent to this vertex
for neighbour in self.graph[v]:
if neighbour not in visited:
self.DFSUtil(neighbour, visited)
# The function to do DFS traversal. It uses
# recursive DFSUtil()
def DFS(self, v):
# Create a set to store visited vertices
visited = set()
# Call the recursive helper function
# to print DFS traversal
self.DFSUtil(v, visited)
# Driver's code
# Create a graph given
# in the above diagram
if __name__ == "__main__":
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
print("Following is DFS from (starting from vertex 2)")
# Function call
g.DFS(2)
# This code is contributed by Neelam Yadav
|
linear
|
linear
|
'''Python3 program to print DFS traversal for complete graph'''
from collections import defaultdict
# this class represents a directed graph using adjacency list representation
class Graph:
# Constructor
def __init__(self):
# default dictionary to store graph
self.graph = defaultdict(list)
# Function to add an edge to graph
def addEdge(self, u, v):
self.graph[u].append(v)
# A function used by DFS
def DFSUtil(self, v, visited):
# Mark the current node as visited and print it
visited.add(v)
print(v, end=" ")
# recur for all the vertices adjacent to this vertex
for neighbour in self.graph[v]:
if neighbour not in visited:
self.DFSUtil(neighbour, visited)
# The function to do DFS traversal. It uses recursive DFSUtil
def DFS(self):
# create a set to store all visited vertices
visited = set()
# call the recursive helper function to print DFS traversal starting from all
# vertices one by one
for vertex in self.graph:
if vertex not in visited:
self.DFSUtil(vertex, visited)
# Driver's code
# create a graph given in the above diagram
if __name__ == "__main__":
print("Following is Depth First Traversal \n")
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
# Function call
g.DFS()
# Improved by Dheeraj Kumar
|
linear
|
linear
|
# Python3 program to find a mother vertex in O(V+E) time
from collections import defaultdict
# This class represents a directed graph using adjacency list
# representation
class Graph:
def __init__(self, vertices):
self.V = vertices # No. of vertices
self.graph = defaultdict(list) # default dictionary
# A recursive function to print DFS starting from v
def DFSUtil(self, v, visited):
# Mark the current node as visited and print it
visited[v] = True
# Recur for all the vertices adjacent to this vertex
for i in self.graph[v]:
if visited[i] == False:
self.DFSUtil(i, visited)
# Add w to the list of v
def addEdge(self, v, w):
self.graph[v].append(w)
# Returns a mother vertex if exists. Otherwise returns -1
def findMother(self):
# visited[] is used for DFS. Initially all are
# initialized as not visited
visited = [False]*(self.V)
# To store last finished vertex (or mother vertex)
v = 0
# Do a DFS traversal and find the last finished
# vertex
for i in range(self.V):
if visited[i] == False:
self.DFSUtil(i, visited)
v = i
# If there exist mother vertex (or vertices) in given
# graph, then v must be one (or one of them)
# Now check if v is actually a mother vertex (or graph
# has a mother vertex). We basically check if every vertex
# is reachable from v or not.
# Reset all values in visited[] as false and do
# DFS beginning from v to check if all vertices are
# reachable from it or not.
visited = [False]*(self.V)
self.DFSUtil(v, visited)
if any(i == False for i in visited):
return -1
else:
return v
# Driver code
if __name__ == '__main__':
g = Graph(7)
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 3)
g.addEdge(4, 1)
g.addEdge(6, 4)
g.addEdge(5, 6)
g.addEdge(5, 2)
g.addEdge(6, 0)
# Function call
print("A mother vertex is " + str(g.findMother()))
# This code is contributed by Neelam Yadav
|
linear
|
linear
|
# Python 3 program to count all paths
# from a source to a destination.
# A directed graph using adjacency
# list representation
class Graph:
def __init__(self, V):
self.V = V
self.adj = [[] for i in range(V)]
def addEdge(self, u, v):
# Add v to u’s list.
self.adj[u].append(v)
# Returns count of paths from 's' to 'd'
def countPaths(self, s, d):
# Mark all the vertices
# as not visited
visited = [False] * self.V
# Call the recursive helper
# function to print all paths
pathCount = [0]
self.countPathsUtil(s, d, visited, pathCount)
return pathCount[0]
# A recursive function to print all paths
# from 'u' to 'd'. visited[] keeps track
# of vertices in current path. path[]
# stores actual vertices and path_index
# is current index in path[]
def countPathsUtil(self, u, d,
visited, pathCount):
visited[u] = True
# If current vertex is same as
# destination, then increment count
if (u == d):
pathCount[0] += 1
# If current vertex is not destination
else:
# Recur for all the vertices
# adjacent to current vertex
i = 0
while i < len(self.adj[u]):
if (not visited[self.adj[u][i]]):
self.countPathsUtil(self.adj[u][i], d,
visited, pathCount)
i += 1
visited[u] = False
# Driver Code
if __name__ == '__main__':
# Create a graph given in the
# above diagram
g = Graph(4)
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(0, 3)
g.addEdge(2, 0)
g.addEdge(2, 1)
g.addEdge(1, 3)
s = 2
d = 3
# Function call
print(g.countPaths(s, d))
# This code is contributed by PranchalK
|
linear
|
np
|
# Python3 Program to determine level
# of each node and print level
import queue
# function to determine level of
# each node starting from x using BFS
def printLevels(graph, V, x):
# array to store level of each node
level = [None] * V
marked = [False] * V
# create a queue
que = queue.Queue()
# enqueue element x
que.put(x)
# initialize level of source
# node to 0
level[x] = 0
# marked it as visited
marked[x] = True
# do until queue is empty
while (not que.empty()):
# get the first element of queue
x = que.get()
# traverse neighbors of node x
for i in range(len(graph[x])):
# b is neighbor of node x
b = graph[x][i]
# if b is not marked already
if (not marked[b]):
# enqueue b in queue
que.put(b)
# level of b is level of x + 1
level[b] = level[x] + 1
# mark b
marked[b] = True
# display all nodes and their levels
print("Nodes", " ", "Level")
for i in range(V):
print(" ", i, " --> ", level[i])
# Driver Code
if __name__ == '__main__':
# adjacency graph for tree
V = 8
graph = [[] for i in range(V)]
graph[0].append(1)
graph[0].append(2)
graph[1].append(3)
graph[1].append(4)
graph[1].append(5)
graph[2].append(5)
graph[2].append(6)
graph[6].append(7)
# call levels function with source as 0
printLevels(graph, V, 0)
# This code is contributed by PranchalK
|
linear
|
linear
|
# Python3 program to find out path in
# a rectangle containing circles.
import math
import queue
# Function to find out if there is
# any possible path or not.
def isPossible(m, n, k, r, X, Y):
# Take an array of m*n size and
# initialize each element to 0.
rect = [[0] * n for i in range(m)]
# Now using Pythagorean theorem find if a
# cell touches or within any circle or not.
for i in range(m):
for j in range(n):
for p in range(k):
if (math.sqrt((pow((X[p] - 1 - i), 2) +
pow((Y[p] - 1 - j), 2))) <= r):
rect[i][j] = -1
# If the starting cell comes within
# any circle return false.
if (rect[0][0] == -1):
return False
# Now use BFS to find if there
# is any possible path or not.
# Initialize the queue which holds
# the discovered cells whose neighbors
# are not discovered yet.
qu = queue.Queue()
rect[0][0] = 1
qu.put([0, 0])
# Discover cells until queue is not empty
while (not qu.empty()):
arr = qu.get()
elex = arr[0]
eley = arr[1]
# Discover the eight adjacent nodes.
# check top-left cell
if ((elex > 0) and (eley > 0) and
(rect[elex - 1][eley - 1] == 0)):
rect[elex - 1][eley - 1] = 1
v = [elex - 1, eley - 1]
qu.put(v)
# check top cell
if ((elex > 0) and
(rect[elex - 1][eley] == 0)):
rect[elex - 1][eley] = 1
v = [elex - 1, eley]
qu.put(v)
# check top-right cell
if ((elex > 0) and (eley < n - 1) and
(rect[elex - 1][eley + 1] == 0)):
rect[elex - 1][eley + 1] = 1
v = [elex - 1, eley + 1]
qu.put(v)
# check left cell
if ((eley > 0) and
(rect[elex][eley - 1] == 0)):
rect[elex][eley - 1] = 1
v = [elex, eley - 1]
qu.put(v)
# check right cell
if ((eley < n - 1) and
(rect[elex][eley + 1] == 0)):
rect[elex][eley + 1] = 1
v = [elex, eley + 1]
qu.put(v)
# check bottom-left cell
if ((elex < m - 1) and (eley > 0) and
(rect[elex + 1][eley - 1] == 0)):
rect[elex + 1][eley - 1] = 1
v = [elex + 1, eley - 1]
qu.put(v)
# check bottom cell
if ((elex < m - 1) and
(rect[elex + 1][eley] == 0)):
rect[elex + 1][eley] = 1
v = [elex + 1, eley]
qu.put(v)
# check bottom-right cell
if ((elex < m - 1) and (eley < n - 1) and
(rect[elex + 1][eley + 1] == 0)):
rect[elex + 1][eley + 1] = 1
v = [elex + 1, eley + 1]
qu.put(v)
# Now if the end cell (i.e. bottom right cell)
# is 1(reachable) then we will send true.
return (rect[m - 1][n - 1] == 1)
# Driver Code
if __name__ == '__main__':
# Test case 1
m1 = 5
n1 = 5
k1 = 2
r1 = 1
X1 = [1, 3]
Y1 = [3, 3]
# Function call
if (isPossible(m1, n1, k1, r1, X1, Y1)):
print("Possible")
else:
print("Not Possible")
# Test case 2
m2 = 5
n2 = 5
k2 = 2
r2 = 1
X2 = [1, 1]
Y2 = [2, 3]
# Function call
if (isPossible(m2, n2, k2, r2, X2, Y2)):
print("Possible")
else:
print("Not Possible")
# This code is contributed by PranchalK
|
quadratic
|
quadratic
|
# Python3 program to print all paths of
# source to destination in given graph
from typing import List
from collections import deque
# Utility function for printing
# the found path in graph
def printpath(path: List[int]) -> None:
size = len(path)
for i in range(size):
print(path[i], end = " ")
print()
# Utility function to check if current
# vertex is already present in path
def isNotVisited(x: int, path: List[int]) -> int:
size = len(path)
for i in range(size):
if (path[i] == x):
return 0
return 1
# Utility function for finding paths in graph
# from source to destination
def findpaths(g: List[List[int]], src: int,
dst: int, v: int) -> None:
# Create a queue which stores
# the paths
q = deque()
# Path vector to store the current path
path = []
path.append(src)
q.append(path.copy())
while q:
path = q.popleft()
last = path[len(path) - 1]
# If last vertex is the desired destination
# then print the path
if (last == dst):
printpath(path)
# Traverse to all the nodes connected to
# current vertex and push new path to queue
for i in range(len(g[last])):
if (isNotVisited(g[last][i], path)):
newpath = path.copy()
newpath.append(g[last][i])
q.append(newpath)
# Driver code
if __name__ == "__main__":
# Number of vertices
v = 4
g = [[] for _ in range(4)]
# Construct a graph
g[0].append(3)
g[0].append(1)
g[0].append(2)
g[1].append(3)
g[2].append(0)
g[2].append(1)
src = 2
dst = 3
print("path from src {} to dst {} are".format(
src, dst))
# Function for finding the paths
findpaths(g, src, dst, v)
# This code is contributed by sanjeev2552
|
quadratic
|
quadratic
|
# Python3 program to find minimum edge
# between given two vertex of Graph
import queue
# function for finding minimum
# no. of edge using BFS
def minEdgeBFS(edges, u, v, n):
# visited[n] for keeping track
# of visited node in BFS
visited = [0] * n
# Initialize distances as 0
distance = [0] * n
# queue to do BFS.
Q = queue.Queue()
distance[u] = 0
Q.put(u)
visited[u] = True
while (not Q.empty()):
x = Q.get()
for i in range(len(edges[x])):
if (visited[edges[x][i]]):
continue
# update distance for i
distance[edges[x][i]] = distance[x] + 1
Q.put(edges[x][i])
visited[edges[x][i]] = 1
return distance[v]
# function for addition of edge
def addEdge(edges, u, v):
edges[u].append(v)
edges[v].append(u)
# Driver Code
if __name__ == '__main__':
# To store adjacency list of graph
n = 9
edges = [[] for i in range(n)]
addEdge(edges, 0, 1)
addEdge(edges, 0, 7)
addEdge(edges, 1, 7)
addEdge(edges, 1, 2)
addEdge(edges, 2, 3)
addEdge(edges, 2, 5)
addEdge(edges, 2, 8)
addEdge(edges, 3, 4)
addEdge(edges, 3, 5)
addEdge(edges, 4, 5)
addEdge(edges, 5, 6)
addEdge(edges, 6, 7)
addEdge(edges, 7, 8)
u = 0
v = 5
print(minEdgeBFS(edges, u, v, n))
# This code is contributed by PranchalK
|
linear
|
linear
|
# Python3 code to find minimum steps to reach
# to specific cell in minimum moves by Knight
class cell:
def __init__(self, x=0, y=0, dist=0):
self.x = x
self.y = y
self.dist = dist
# checks whether given position is
# inside the board
def isInside(x, y, N):
if (x >= 1 and x <= N and
y >= 1 and y <= N):
return True
return False
# Method returns minimum step to reach
# target position
def minStepToReachTarget(knightpos,
targetpos, N):
# all possible movements for the knight
dx = [2, 2, -2, -2, 1, 1, -1, -1]
dy = [1, -1, 1, -1, 2, -2, 2, -2]
queue = []
# push starting position of knight
# with 0 distance
queue.append(cell(knightpos[0], knightpos[1], 0))
# make all cell unvisited
visited = [[False for i in range(N + 1)]
for j in range(N + 1)]
# visit starting state
visited[knightpos[0]][knightpos[1]] = True
# loop until we have one element in queue
while(len(queue) > 0):
t = queue[0]
queue.pop(0)
# if current cell is equal to target
# cell, return its distance
if(t.x == targetpos[0] and
t.y == targetpos[1]):
return t.dist
# iterate for all reachable states
for i in range(8):
x = t.x + dx[i]
y = t.y + dy[i]
if(isInside(x, y, N) and not visited[x][y]):
visited[x][y] = True
queue.append(cell(x, y, t.dist + 1))
# Driver Code
if __name__ == '__main__':
N = 30
knightpos = [1, 1]
targetpos = [30, 30]
# Function call
print(minStepToReachTarget(knightpos,
targetpos, N))
# This code is contributed by
# Kaustav kumar Chanda
|
quadratic
|
quadratic
|
# Python program to detect cycle
# in a graph
from collections import defaultdict
class Graph():
def __init__(self,vertices):
self.graph = defaultdict(list)
self.V = vertices
def addEdge(self,u,v):
self.graph[u].append(v)
def isCyclicUtil(self, v, visited, recStack):
# Mark current node as visited and
# adds to recursion stack
visited[v] = True
recStack[v] = True
# Recur for all neighbours
# if any neighbour is visited and in
# recStack then graph is cyclic
for neighbour in self.graph[v]:
if visited[neighbour] == False:
if self.isCyclicUtil(neighbour, visited, recStack) == True:
return True
elif recStack[neighbour] == True:
return True
# The node needs to be popped from
# recursion stack before function ends
recStack[v] = False
return False
# Returns true if graph is cyclic else false
def isCyclic(self):
visited = [False] * (self.V + 1)
recStack = [False] * (self.V + 1)
for node in range(self.V):
if visited[node] == False:
if self.isCyclicUtil(node,visited,recStack) == True:
return True
return False
g = Graph(4)
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
if g.isCyclic() == 1:
print "Graph contains cycle"
else:
print "Graph doesn't contain cycle"
# Thanks to Divyanshu Mehta for contributing this code
|
linear
|
linear
|
# Python Program to detect cycle in an undirected graph
from collections import defaultdict
# This class represents a undirected
# graph using adjacency list representation
class Graph:
def __init__(self, vertices):
# No. of vertices
self.V = vertices # No. of vertices
# Default dictionary to store graph
self.graph = defaultdict(list)
# Function to add an edge to graph
def addEdge(self, v, w):
# Add w to v_s list
self.graph[v].append(w)
# Add v to w_s list
self.graph[w].append(v)
# A recursive function that uses
# visited[] and parent to detect
# cycle in subgraph reachable from vertex v.
def isCyclicUtil(self, v, visited, parent):
# Mark the current node as visited
visited[v] = True
# Recur for all the vertices
# adjacent to this vertex
for i in self.graph[v]:
# If the node is not
# visited then recurse on it
if visited[i] == False:
if(self.isCyclicUtil(i, visited, v)):
return True
# If an adjacent vertex is
# visited and not parent
# of current vertex,
# then there is a cycle
elif parent != i:
return True
return False
# Returns true if the graph
# contains a cycle, else false.
def isCyclic(self):
# Mark all the vertices
# as not visited
visited = [False]*(self.V)
# Call the recursive helper
# function to detect cycle in different
# DFS trees
for i in range(self.V):
# Don't recur for u if it
# is already visited
if visited[i] == False:
if(self.isCyclicUtil
(i, visited, -1)) == True:
return True
return False
# Create a graph given in the above diagram
g = Graph(5)
g.addEdge(1, 0)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(0, 3)
g.addEdge(3, 4)
if g.isCyclic():
print("Graph contains cycle")
else:
print("Graph doesn't contain cycle ")
g1 = Graph(3)
g1.addEdge(0, 1)
g1.addEdge(1, 2)
if g1.isCyclic():
print("Graph contains cycle")
else:
print("Graph doesn't contain cycle ")
# This code is contributed by Neelam Yadav
|
linear
|
linear
|
# Python program to detect cycle in
# a directed graph
from collections import defaultdict
class Graph():
def __init__(self, V):
self.V = V
self.graph = defaultdict(list)
def addEdge(self, u, v):
self.graph[u].append(v)
def DFSUtil(self, u, color):
# GRAY : This vertex is being processed (DFS
# for this vertex has started, but not
# ended (or this vertex is in function
# call stack)
color[u] = "GRAY"
for v in self.graph[u]:
if color[v] == "GRAY":
return True
if color[v] == "WHITE" and self.DFSUtil(v, color) == True:
return True
color[u] = "BLACK"
return False
def isCyclic(self):
color = ["WHITE"] * self.V
for i in range(self.V):
if color[i] == "WHITE":
if self.DFSUtil(i, color) == True:
return True
return False
# Driver program to test above functions
g = Graph(4)
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
print ("Graph contains cycle" if g.isCyclic() == True\
else "Graph doesn't contain cycle")
# This program is contributed by Divyanshu Mehta
|
linear
|
linear
|
# Python3 program to check if there
# is a cycle of total odd weight
# This function returns true if the current subpart
# of the forest is two colorable, else false.
def twoColorUtil(G, src, N, colorArr):
# Assign first color to source
colorArr[src] = 1
# Create a queue (FIFO) of vertex numbers and
# enqueue source vertex for BFS traversal
q = [src]
# Run while there are vertices in queue
# (Similar to BFS)
while len(q) > 0:
u = q.pop(0)
# Find all non-colored adjacent vertices
for v in range(0, len(G[u])):
# An edge from u to v exists and
# destination v is not colored
if colorArr[G[u][v]] == -1:
# Assign alternate color to this
# adjacent v of u
colorArr[G[u][v]] = 1 - colorArr[u]
q.append(G[u][v])
# An edge from u to v exists and destination
# v is colored with same color as u
elif colorArr[G[u][v]] == colorArr[u]:
return False
return True
# This function returns true if graph
# G[V][V] is two colorable, else false
def twoColor(G, N):
# Create a color array to store colors assigned
# to all vertices. Vertex number is used as index
# in this array. The value '-1' of colorArr[i]
# is used to indicate that no color is assigned
# to vertex 'i'. The value 1 is used to indicate
# first color is assigned and value 0 indicates
# second color is assigned.
colorArr = [-1] * N
# As we are dealing with graph, the input might
# come as a forest, thus start coloring from a
# node and if true is returned we'll know that
# we successfully colored the subpart of our
# forest and we start coloring again from a new
# uncolored node. This way we cover the entire forest.
for i in range(N):
if colorArr[i] == -1:
if twoColorUtil(G, i, N, colorArr) == False:
return False
return True
# Returns false if an odd cycle is present else true
# int info[][] is the information about our graph
# int n is the number of nodes
# int m is the number of informations given to us
def isOddSum(info, n, m):
# Declaring adjacency list of a graph
# Here at max, we can encounter all the
# edges with even weight thus there will
# be 1 pseudo node for each edge
G = [[] for i in range(2*n)]
pseudo, pseudo_count = n+1, 0
for i in range(0, m):
# For odd weight edges, we
# directly add it in our graph
if info[i][2] % 2 == 1:
u, v = info[i][0], info[i][1]
G[u].append(v)
G[v].append(u)
# For even weight edges, we break it
else:
u, v = info[i][0], info[i][1]
# Entering a pseudo node between u---v
G[u].append(pseudo)
G[pseudo].append(u)
G[v].append(pseudo)
G[pseudo].append(v)
# Keeping a record of number
# of pseudo nodes inserted
pseudo_count += 1
# Making a new pseudo node for next time
pseudo += 1
# We pass number graph G[][] and total number
# of node = actual number of nodes + number of
# pseudo nodes added.
return twoColor(G, n+pseudo_count)
# Driver function
if __name__ == "__main__":
# 'n' correspond to number of nodes in our
# graph while 'm' correspond to the number
# of information about this graph.
n, m = 4, 3
info = [[1, 2, 12],
[2, 3, 1],
[4, 3, 1],
[4, 1, 20]]
# This function break the even weighted edges in
# two parts. Makes the adjacency representation
# of the graph and sends it for two coloring.
if isOddSum(info, n, m) == True:
print("No")
else:
print("Yes")
# This code is contributed by Rituraj Jain
|
linear
|
quadratic
|
# Python3 program to implement Union-Find
# with union by rank and path compression.
# set parent of every node to itself
# and size of node to one
def initialize(n):
global Arr, size
for i in range(n + 1):
Arr[i] = i
size[i] = 1
# Each time we follow a path, find
# function compresses it further
# until the path length is greater
# than or equal to 1.
def find(i):
global Arr, size
# while we reach a node whose
# parent is equal to itself
while (Arr[i] != i):
Arr[i] = Arr[Arr[i]] # Skip one level
i = Arr[i] # Move to the new level
return i
# A function that does union of two
# nodes x and y where xr is root node
# of x and yr is root node of y
def _union(xr, yr):
global Arr, size
if (size[xr] < size[yr]): # Make yr parent of xr
Arr[xr] = Arr[yr]
size[yr] += size[xr]
else: # Make xr parent of yr
Arr[yr] = Arr[xr]
size[xr] += size[yr]
# The main function to check whether
# a given graph contains cycle or not
def isCycle(adj, V):
global Arr, size
# Iterate through all edges of graph,
# find nodes connecting them.
# If root nodes of both are same,
# then there is cycle in graph.
for i in range(V):
for j in range(len(adj[i])):
x = find(i) # find root of i
y = find(adj[i][j]) # find root of adj[i][j]
if (x == y):
return 1 # If same parent
_union(x, y) # Make them connect
return 0
# Driver Code
MAX_VERTEX = 101
# Arr to represent parent of index i
Arr = [None] * MAX_VERTEX
# Size to represent the number of nodes
# in subgraph rooted at index i
size = [None] * MAX_VERTEX
V = 3
# Initialize the values for array
# Arr and Size
initialize(V)
# Let us create following graph
# 0
# | \
# | \
# 1-----2
# Adjacency list for graph
adj = [[] for i in range(V)]
adj[0].append(1)
adj[0].append(2)
adj[1].append(2)
# call is_cycle to check if it
# contains cycle
if (isCycle(adj, V)):
print("Graph contains Cycle.")
else:
print("Graph does not contain Cycle.")
# This code is contributed by PranchalK
|
constant
|
logn
|
# Python3 program to find number of magical
# indices in the given array.
# Function to count number of magical
# indices.
def solve(A, n) :
cnt = 0
# Array to store parent node of
# traversal.
parent = [None] * (n + 1)
# Array to determine whether current node
# is already counted in the cycle.
vis = [None] * (n + 1)
# Initialize the arrays.
for i in range(0, n+1):
parent[i] = -1
vis[i] = 0
for i in range(0, n):
j = i
# Check if current node is already
# traversed or not. If node is not
# traversed yet then parent value
# will be -1.
if (parent[j] == -1) :
# Traverse the graph until an
# already visited node is not
# found.
while (parent[j] == -1) :
parent[j] = i
j = (j + A[j] + 1) % n
# Check parent value to ensure
# a cycle is present.
if (parent[j] == i) :
# Count number of nodes in
# the cycle.
while (vis[j]==0) :
vis[j] = 1
cnt = cnt + 1
j = (j + A[j] + 1) % n
return cnt
# Driver code
A = [ 0, 0, 0, 2 ]
n = len(A)
print (solve(A, n))
# This code is contributed by Manish Shaw
# (manishshaw1)
|
linear
|
linear
|
# Python program to print topological sorting of a DAG
from collections import defaultdict
# Class to represent a graph
class Graph:
def __init__(self, vertices):
self.graph = defaultdict(list) # dictionary containing adjacency List
self.V = vertices # No. of vertices
# function to add an edge to graph
def addEdge(self, u, v):
self.graph[u].append(v)
# A recursive function used by topologicalSort
def topologicalSortUtil(self, v, visited, stack):
# Mark the current node as visited.
visited[v] = True
# Recur for all the vertices adjacent to this vertex
for i in self.graph[v]:
if visited[i] == False:
self.topologicalSortUtil(i, visited, stack)
# Push current vertex to stack which stores result
stack.append(v)
# The function to do Topological Sort. It uses recursive
# topologicalSortUtil()
def topologicalSort(self):
# Mark all the vertices as not visited
visited = [False]*self.V
stack = []
# Call the recursive helper function to store Topological
# Sort starting from all vertices one by one
for i in range(self.V):
if visited[i] == False:
self.topologicalSortUtil(i, visited, stack)
# Print contents of the stack
print(stack[::-1]) # return list in reverse order
# Driver Code
if __name__ == '__main__':
g = Graph(6)
g.addEdge(5, 2)
g.addEdge(5, 0)
g.addEdge(4, 0)
g.addEdge(4, 1)
g.addEdge(2, 3)
g.addEdge(3, 1)
print("Following is a Topological Sort of the given graph")
# Function Call
g.topologicalSort()
# This code is contributed by Neelam Yadav
|
linear
|
linear
|
# Python program to print topological sorting of a DAG
from collections import defaultdict
# Class to represent a graph
class Graph:
def __init__(self, vertices):
self.graph = defaultdict(list) # dictionary containing adjacency List
self.V = vertices # No. of vertices
# function to add an edge to graph
def addEdge(self, u, v):
self.graph[u].append(v)
# neighbors generator given key
def neighbor_gen(self, v):
for k in self.graph[v]:
yield k
# non recursive topological sort
def nonRecursiveTopologicalSortUtil(self, v, visited, stack):
# working stack contains key and the corresponding current generator
working_stack = [(v, self.neighbor_gen(v))]
while working_stack:
# get last element from stack
v, gen = working_stack.pop()
visited[v] = True
# run through neighbor generator until it's empty
for next_neighbor in gen:
if not visited[next_neighbor]: # not seen before?
# remember current work
working_stack.append((v, gen))
# restart with new neighbor
working_stack.append(
(next_neighbor, self.neighbor_gen(next_neighbor)))
break
else:
# no already-visited neighbor (or no more of them)
stack.append(v)
# The function to do Topological Sort.
def nonRecursiveTopologicalSort(self):
# Mark all the vertices as not visited
visited = [False]*self.V
# result stack
stack = []
# Call the helper function to store Topological
# Sort starting from all vertices one by one
for i in range(self.V):
if not(visited[i]):
self.nonRecursiveTopologicalSortUtil(i, visited, stack)
# Print contents of the stack in reverse
stack.reverse()
print(stack)
# Driver code
if __name__ == "__main__":
g = Graph(6)
g.addEdge(5, 2)
g.addEdge(5, 0)
g.addEdge(4, 0)
g.addEdge(4, 1)
g.addEdge(2, 3)
g.addEdge(3, 1)
# Function call
print("The following is a Topological Sort of the given graph")
g.nonRecursiveTopologicalSort()
# This code was based of Neelam Yadav's code, modified by Suhail Alnahari, Python-ified by Matthias Urlichhs
|
linear
|
linear
|
# class to represent a graph object
class Graph:
# Constructor
def __init__(self, edges, N):
# A List of Lists to represent an adjacency list
self.adjList = [[] for _ in range(N)]
# stores in-degree of a vertex
# initialize in-degree of each vertex by 0
self.indegree = [0] * N
# add edges to the undirected graph
for (src, dest) in edges:
# add an edge from source to destination
self.adjList[src].append(dest)
# increment in-degree of destination vertex by 1
self.indegree[dest] = self.indegree[dest] + 1
# Recursive function to find
# all topological orderings of a given DAG
def findAllTopologicalOrders(graph, path, discovered, N):
# do for every vertex
for v in range(N):
# proceed only if in-degree of current node is 0 and
# current node is not processed yet
if graph.indegree[v] == 0 and not discovered[v]:
# for every adjacent vertex u of v,
# reduce in-degree of u by 1
for u in graph.adjList[v]:
graph.indegree[u] = graph.indegree[u] - 1
# include current node in the path
# and mark it as discovered
path.append(v)
discovered[v] = True
# recur
findAllTopologicalOrders(graph, path, discovered, N)
# backtrack: reset in-degree
# information for the current node
for u in graph.adjList[v]:
graph.indegree[u] = graph.indegree[u] + 1
# backtrack: remove current node from the path and
# mark it as undiscovered
path.pop()
discovered[v] = False
# print the topological order if
# all vertices are included in the path
if len(path) == N:
print(path)
# Print all topological orderings of a given DAG
def printAllTopologicalOrders(graph):
# get number of nodes in the graph
N = len(graph.adjList)
# create an auxiliary space to keep track of whether vertex is discovered
discovered = [False] * N
# list to store the topological order
path = []
# find all topological ordering and print them
findAllTopologicalOrders(graph, path, discovered, N)
# Driver code
if __name__ == '__main__':
# List of graph edges as per above diagram
edges = [(5, 2), (5, 0), (4, 0), (4, 1), (2, 3), (3, 1)]
print("All Topological sorts")
# Number of nodes in the graph
N = 6
# create a graph from edges
graph = Graph(edges, N)
# print all topological ordering of the graph
printAllTopologicalOrders(graph)
# This code is contributed by Priyadarshini Kumari
|
linear
|
quadratic
|
# A Python program to print topological sorting of a graph
# using indegrees
from collections import defaultdict
# Class to represent a graph
class Graph:
def __init__(self, vertices):
self.graph = defaultdict(list) # dictionary containing adjacency List
self.V = vertices # No. of vertices
# function to add an edge to graph
def addEdge(self, u, v):
self.graph[u].append(v)
# The function to do Topological Sort.
def topologicalSort(self):
# Create a vector to store indegrees of all
# vertices. Initialize all indegrees as 0.
in_degree = [0]*(self.V)
# Traverse adjacency lists to fill indegrees of
# vertices. This step takes O(V + E) time
for i in self.graph:
for j in self.graph[i]:
in_degree[j] += 1
# Create an queue and enqueue all vertices with
# indegree 0
queue = []
for i in range(self.V):
if in_degree[i] == 0:
queue.append(i)
# Initialize count of visited vertices
cnt = 0
# Create a vector to store result (A topological
# ordering of the vertices)
top_order = []
# One by one dequeue vertices from queue and enqueue
# adjacents if indegree of adjacent becomes 0
while queue:
# Extract front of queue (or perform dequeue)
# and add it to topological order
u = queue.pop(0)
top_order.append(u)
# Iterate through all neighbouring nodes
# of dequeued node u and decrease their in-degree
# by 1
for i in self.graph[u]:
in_degree[i] -= 1
# If in-degree becomes zero, add it to queue
if in_degree[i] == 0:
queue.append(i)
cnt += 1
# Check if there was a cycle
if cnt != self.V:
print ("There exists a cycle in the graph")
else :
# Print topological order
print (top_order)
g = Graph(6)
g.addEdge(5, 2);
g.addEdge(5, 0);
g.addEdge(4, 0);
g.addEdge(4, 1);
g.addEdge(2, 3);
g.addEdge(3, 1);
print ("Following is a Topological Sort of the given graph")
g.topologicalSort()
# This code is contributed by Neelam Yadav
|
linear
|
linear
|
# A Python3 program for Prim's Minimum Spanning Tree (MST) algorithm.
# The program is for adjacency matrix representation of the graph
import sys # Library for INT_MAX
class Graph():
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]
# A utility function to print the constructed MST stored in parent[]
def printMST(self, parent):
print("Edge \tWeight")
for i in range(1, self.V):
print(parent[i], "-", i, "\t", self.graph[i][parent[i]])
# A utility function to find the vertex with
# minimum distance value, from the set of vertices
# not yet included in shortest path tree
def minKey(self, key, mstSet):
# Initialize min value
min = sys.maxsize
for v in range(self.V):
if key[v] < min and mstSet[v] == False:
min = key[v]
min_index = v
return min_index
# Function to construct and print MST for a graph
# represented using adjacency matrix representation
def primMST(self):
# Key values used to pick minimum weight edge in cut
key = [sys.maxsize] * self.V
parent = [None] * self.V # Array to store constructed MST
# Make key 0 so that this vertex is picked as first vertex
key[0] = 0
mstSet = [False] * self.V
parent[0] = -1 # First node is always the root of
for cout in range(self.V):
# Pick the minimum distance vertex from
# the set of vertices not yet processed.
# u is always equal to src in first iteration
u = self.minKey(key, mstSet)
# Put the minimum distance vertex in
# the shortest path tree
mstSet[u] = True
# Update dist value of the adjacent vertices
# of the picked vertex only if the current
# distance is greater than new distance and
# the vertex in not in the shortest path tree
for v in range(self.V):
# graph[u][v] is non zero only for adjacent vertices of m
# mstSet[v] is false for vertices not yet included in MST
# Update the key only if graph[u][v] is smaller than key[v]
if self.graph[u][v] > 0 and mstSet[v] == False and key[v] > self.graph[u][v]:
key[v] = self.graph[u][v]
parent[v] = u
self.printMST(parent)
# Driver's code
if __name__ == '__main__':
g = Graph(5)
g.graph = [[0, 2, 0, 6, 0],
[2, 0, 3, 8, 5],
[0, 3, 0, 0, 7],
[6, 8, 0, 0, 9],
[0, 5, 7, 9, 0]]
g.primMST()
# Contributed by Divyanshu Mehta
|
linear
|
quadratic
|
# Python program for Kruskal's algorithm to find
# Minimum Spanning Tree of a given connected,
# undirected and weighted graph
# Class to represent a graph
class Graph:
def __init__(self, vertices):
self.V = vertices # No. of vertices
self.graph = []
# to store graph
# function to add an edge to graph
def addEdge(self, u, v, w):
self.graph.append([u, v, w])
# A utility function to find set of an element i
# (truly uses path compression technique)
def find(self, parent, i):
if parent[i] != i:
# Reassignment of node's parent to root node as
# path compression requires
parent[i] = self.find(parent, parent[i])
return parent[i]
# A function that does union of two sets of x and y
# (uses union by rank)
def union(self, parent, rank, x, y):
# Attach smaller rank tree under root of
# high rank tree (Union by Rank)
if rank[x] < rank[y]:
parent[x] = y
elif rank[x] > rank[y]:
parent[y] = x
# If ranks are same, then make one as root
# and increment its rank by one
else:
parent[y] = x
rank[x] += 1
# The main function to construct MST using Kruskal's
# algorithm
def KruskalMST(self):
result = [] # This will store the resultant MST
# An index variable, used for sorted edges
i = 0
# An index variable, used for result[]
e = 0
# Step 1: Sort all the edges in
# non-decreasing order of their
# weight. If we are not allowed to change the
# given graph, we can create a copy of graph
self.graph = sorted(self.graph,
key=lambda item: item[2])
parent = []
rank = []
# Create V subsets with single elements
for node in range(self.V):
parent.append(node)
rank.append(0)
# Number of edges to be taken is equal to V-1
while e < self.V - 1:
# Step 2: Pick the smallest edge and increment
# the index for next iteration
u, v, w = self.graph[i]
i = i + 1
x = self.find(parent, u)
y = self.find(parent, v)
# If including this edge doesn't
# cause cycle, then include it in result
# and increment the index of result
# for next edge
if x != y:
e = e + 1
result.append([u, v, w])
self.union(parent, rank, x, y)
# Else discard the edge
minimumCost = 0
print("Edges in the constructed MST")
for u, v, weight in result:
minimumCost += weight
print("%d -- %d == %d" % (u, v, weight))
print("Minimum Spanning Tree", minimumCost)
# Driver's code
if __name__ == '__main__':
g = Graph(4)
g.addEdge(0, 1, 10)
g.addEdge(0, 2, 6)
g.addEdge(0, 3, 5)
g.addEdge(1, 3, 15)
g.addEdge(2, 3, 4)
# Function call
g.KruskalMST()
# This code is contributed by Neelam Yadav
# Improved by James Graça-Jones
|
linear
|
nlogn
|
# Python3 program to solve N Queen
# Problem using backtracking
global N
N = 4
def printSolution(board):
for i in range(N):
for j in range(N):
print(board[i][j], end = " ")
print()
# A utility function to check if a queen can
# be placed on board[row][col]. Note that this
# function is called when "col" queens are
# already placed in columns from 0 to col -1.
# So we need to check only left side for
# attacking queens
def isSafe(board, row, col):
# Check this row on left side
for i in range(col):
if board[row][i] == 1:
return False
# Check upper diagonal on left side
for i, j in zip(range(row, -1, -1),
range(col, -1, -1)):
if board[i][j] == 1:
return False
# Check lower diagonal on left side
for i, j in zip(range(row, N, 1),
range(col, -1, -1)):
if board[i][j] == 1:
return False
return True
def solveNQUtil(board, col):
# base case: If all queens are placed
# then return true
if col >= N:
return True
# Consider this column and try placing
# this queen in all rows one by one
for i in range(N):
if isSafe(board, i, col):
# Place this queen in board[i][col]
board[i][col] = 1
# recur to place rest of the queens
if solveNQUtil(board, col + 1) == True:
return True
# If placing queen in board[i][col
# doesn't lead to a solution, then
# queen from board[i][col]
board[i][col] = 0
# if the queen can not be placed in any row in
# this column col then return false
return False
# This function solves the N Queen problem using
# Backtracking. It mainly uses solveNQUtil() to
# solve the problem. It returns false if queens
# cannot be placed, otherwise return true and
# placement of queens in the form of 1s.
# note that there may be more than one
# solutions, this function prints one of the
# feasible solutions.
def solveNQ():
board = [ [0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0] ]
if solveNQUtil(board, 0) == False:
print ("Solution does not exist")
return False
printSolution(board)
return True
# Driver Code
solveNQ()
# This code is contributed by Divyanshu Mehta
|
quadratic
|
np
|
""" Python3 program to solve N Queen Problem using
backtracking """
N = 4
""" ld is an array where its indices indicate row-col+N-1
(N-1) is for shifting the difference to store negative
indices """
ld = [0] * 30
""" rd is an array where its indices indicate row+col
and used to check whether a queen can be placed on
right diagonal or not"""
rd = [0] * 30
"""column array where its indices indicates column and
used to check whether a queen can be placed in that
row or not"""
cl = [0] * 30
""" A utility function to print solution """
def printSolution(board):
for i in range(N):
for j in range(N):
print(board[i][j], end = " ")
print()
""" A recursive utility function to solve N
Queen problem """
def solveNQUtil(board, col):
""" base case: If all queens are placed
then return True """
if (col >= N):
return True
""" Consider this column and try placing
this queen in all rows one by one """
for i in range(N):
""" Check if the queen can be placed on board[i][col] """
""" A check if a queen can be placed on board[row][col].
We just need to check ld[row-col+n-1] and rd[row+coln]
where ld and rd are for left and right diagonal respectively"""
if ((ld[i - col + N - 1] != 1 and
rd[i + col] != 1) and cl[i] != 1):
""" Place this queen in board[i][col] """
board[i][col] = 1
ld[i - col + N - 1] = rd[i + col] = cl[i] = 1
""" recur to place rest of the queens """
if (solveNQUtil(board, col + 1)):
return True
""" If placing queen in board[i][col]
doesn't lead to a solution,
then remove queen from board[i][col] """
board[i][col] = 0 # BACKTRACK
ld[i - col + N - 1] = rd[i + col] = cl[i] = 0
""" If the queen cannot be placed in
any row in this column col then return False """
return False
""" This function solves the N Queen problem using
Backtracking. It mainly uses solveNQUtil() to
solve the problem. It returns False if queens
cannot be placed, otherwise, return True and
prints placement of queens in the form of 1s.
Please note that there may be more than one
solutions, this function prints one of the
feasible solutions."""
def solveNQ():
board = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
if (solveNQUtil(board, 0) == False):
printf("Solution does not exist")
return False
printSolution(board)
return True
# Driver Code
solveNQ()
# This code is contributed by SHUBHAMSINGH10
|
linear
|
np
|
# Python3 program for the above approach
# Number of vertices in the graph
# define 4 4
# check if the colored
# graph is safe or not
def isSafe(graph, color):
# check for every edge
for i in range(4):
for j in range(i + 1, 4):
if (graph[i][j] and color[j] == color[i]):
return False
return True
# /* This function solves the m Coloring
# problem using recursion. It returns
# false if the m colours cannot be assigned,
# otherwise, return true and prints
# assignments of colours to all vertices.
# Please note that there may be more than
# one solutions, this function prints one
# of the feasible solutions.*/
def graphColoring(graph, m, i, color):
# if current index reached end
if (i == 4):
# if coloring is safe
if (isSafe(graph, color)):
# Print the solution
printSolution(color)
return True
return False
# Assign each color from 1 to m
for j in range(1, m + 1):
color[i] = j
# Recur of the rest vertices
if (graphColoring(graph, m, i + 1, color)):
return True
color[i] = 0
return False
# /* A utility function to print solution */
def printSolution(color):
print("Solution Exists:" " Following are the assigned colors ")
for i in range(4):
print(color[i], end=" ")
# Driver code
if __name__ == '__main__':
# /* Create following graph and
# test whether it is 3 colorable
# (3)---(2)
# | / |
# | / |
# | / |
# (0)---(1)
# */
graph = [
[0, 1, 1, 1],
[1, 0, 1, 0],
[1, 1, 0, 1],
[1, 0, 1, 0],
]
m = 3 # Number of colors
# Initialize all color values as 0.
# This initialization is needed
# correct functioning of isSafe()
color = [0 for i in range(4)]
# Function call
if (not graphColoring(graph, m, 0, color)):
print("Solution does not exist")
# This code is contributed by mohit kumar 29
|
linear
|
quadratic
|
# Python3 program for solution of M Coloring
# problem using backtracking
class Graph():
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]
# A utility function to check
# if the current color assignment
# is safe for vertex v
def isSafe(self, v, colour, c):
for i in range(self.V):
if self.graph[v][i] == 1 and colour[i] == c:
return False
return True
# A recursive utility function to solve m
# coloring problem
def graphColourUtil(self, m, colour, v):
if v == self.V:
return True
for c in range(1, m + 1):
if self.isSafe(v, colour, c) == True:
colour[v] = c
if self.graphColourUtil(m, colour, v + 1) == True:
return True
colour[v] = 0
def graphColouring(self, m):
colour = [0] * self.V
if self.graphColourUtil(m, colour, 0) == None:
return False
# Print the solution
print("Solution exist and Following are the assigned colours:")
for c in colour:
print(c, end=' ')
return True
# Driver Code
if __name__ == '__main__':
g = Graph(4)
g.graph = [[0, 1, 1, 1], [1, 0, 1, 0], [1, 1, 0, 1], [1, 0, 1, 0]]
m = 3
# Function call
g.graphColouring(m)
# This code is contributed by Divyanshu Mehta
|
linear
|
quadratic
|
# Python3 program for the above approach
from queue import Queue
class node:
color = 1
edges = set()
def canPaint(nodes, n, m):
# Create a visited array of n
# nodes, initialized to zero
visited = [0 for _ in range(n+1)]
# maxColors used till now are 1 as
# all nodes are painted color 1
maxColors = 1
# Do a full BFS traversal from
# all unvisited starting points
for _ in range(1, n + 1):
if visited[_]:
continue
# If the starting point is unvisited,
# mark it visited and push it in queue
visited[_] = 1
q = Queue()
q.put(_)
# BFS Travel starts here
while not q.empty():
top = q.get()
# Checking all adjacent nodes
# to "top" edge in our queue
for _ in nodes[top].edges:
# IMPORTANT: If the color of the
# adjacent node is same, increase it by 1
if nodes[top].color == nodes[_].color:
nodes[_].color += 1
# If number of colors used shoots m,
# return 0
maxColors = max(maxColors, max(
nodes[top].color, nodes[_].color))
if maxColors > m:
print(maxColors)
return 0
# If the adjacent node is not visited,
# mark it visited and push it in queue
if not visited[_]:
visited[_] = 1
q.put(_)
return 1
# Driver code
if __name__ == "__main__":
n = 4
graph = [[0, 1, 1, 1],
[1, 0, 1, 0],
[1, 1, 0, 1],
[1, 0, 1, 0]]
# Number of colors
m = 3
# Create a vector of n+1
# nodes of type "node"
# The zeroth position is just
# dummy (1 to n to be used)
nodes = []
for _ in range(n+1):
nodes.append(node())
# Add edges to each node as
# per given input
for _ in range(n):
for __ in range(n):
if graph[_][__]:
# Connect the undirected graph
nodes[_].edges.add(_)
nodes[__].edges.add(__)
# Function call
print(canPaint(nodes, n, m))
# This code is contributed by harshitkap00r
|
linear
|
linear
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.