# Python3 program to print all levels
# with odd and even number of nodes
# Function for BFS in a tree
def bfs(node, parent, height, vis, tree):
# mark first node as visited
vis[node] = 1
# Declare Queue
q = []
# append the first element
q.append(1)
# calculate the level of every node
height[node] = 1 + height[parent]
# Check if the queue is empty or not
while (len(q)):
# Get the top element in
# the queue
top = q[0]
# pop the element
q.pop(0)
# mark as visited
vis[top] = 1
# Iterate for the connected nodes
for i in range(len(tree[top])):
# if not visited
if (not vis[tree[top][i]]):
# Insert into queue
q.append(tree[top][i])
# Increase level
height[tree[top][i]] = 1 + height[top]
# Function to insert edges
def insertEdges(x, y, tree):
tree[x].append(y)
tree[y].append(x)
# Function to print all levels
def printLevelsOddEven(N, vis, height):
mark = [0] * (N + 1)
maxLevel = 0
for i in range(1, N + 1):
# count number of nodes
# in every level
if (vis[i]) :
mark[height[i]] += 1
# find the maximum height of tree
maxLevel = max(height[i], maxLevel)
# print odd number of nodes
print("The levels with odd number",
"of nodes are:", end = " ")
for i in range(1, maxLevel + 1):
if (mark[i] % 2):
print(i, end = " " )
# print even number of nodes
print("\nThe levels with even number",
"of nodes are:", end = " ")
for i in range(1, maxLevel ):
if (mark[i] % 2 == 0):
print(i, end = " ")
# Driver Code
if __name__ == '__main__':
# Construct the tree
""" 1
/ \
2 3
/ \ \
4 5 6
/ \ /
7 8 9 """
N = 9
tree = [[0]] * (N + 1)
insertEdges(1, 2, tree)
insertEdges(1, 3, tree)
insertEdges(2, 4, tree)
insertEdges(2, 5, tree)
insertEdges(5, 7, tree)
insertEdges(5, 8, tree)
insertEdges(3, 6, tree)
insertEdges(6, 9, tree)
height = [0] * (N + 1)
vis = [0] * (N + 1)
# call the bfs function
bfs(1, 0, height, vis, tree)
# Function to print
printLevelsOddEven(N, vis, height)
# This code is contributed
# by SHUBHAMSINGH10