Question: Q ) Given a binary tree, count the total number of magic parents, where a node which is not NULL and has both left and

Q) Given a binary tree, count the total number of magic parents, where a node which is not NULL and has both left and right children and the sum of the number of nodes in the left subtree is odd and that of right subtree is even (or sum of nodes in the left subtree as even and right subtree as odd) should be considered as a magic parent. Node 1 is always the Root node
Input format:
The node_number string(representing the relative position of the node wrt root node,i.e node 1).
E.g:
This is representing a tree having a root node as 1 and 2 is the left child of node 1 and 3 is the right child of node 1 and 5 is the left child of node 3.
2 L
3 R
5 RL
SOLUTION -
class TreeNode:
def __init__(self, val=0):
self.val = val
self.left = None
self.right = None
def build_tree(instructions):
nodes ={1: TreeNode(1)} # Root node
for instruction in instructions:
node_val, path = instruction.split()
node_val = int(node_val)
current = nodes[1] # Start from root
# Traverse the path to insert the node in correct position
for direction in path[:-1]: # Traverse to the parent node
if direction =='L':
if current.left is None:
current.left = TreeNode()
current = current.left
elif direction =='R':
if current.right is None:
current.right = TreeNode()
current = current.right
# Insert the node at the correct position (last step)
if path[-1]=='L':
current.left = TreeNode(node_val)
elif path[-1]=='R':
current.right = TreeNode(node_val)
# Save the node for further use
nodes[node_val]= current.left if path[-1]=='L' else current.right
return nodes[1]
def count_subtree_nodes(node):
if node is None:
return 0
# Recursively count nodes in left and right subtrees
left_count = count_subtree_nodes(node.left)
right_count = count_subtree_nodes(node.right)
# Check if the current node is a magic parent
if node.left is not None and node.right is not None:
if (left_count %2==0 and right_count %2==1) or (left_count %2==1 and right_count %2==0):
count_subtree_nodes.magic_parents +=1
# Return total nodes in the subtree rooted at current node
return left_count + right_count +1
def count_magic_parents(instructions):
# Build the tree from input instructions
root = build_tree(instructions)
# Initialize a variable to count magic parents
count_subtree_nodes.magic_parents =0
# Count the number of nodes in subtrees and check for magic parents
count_subtree_nodes(root)
return count_subtree_nodes.magic_parents
# Input example:
instructions =["2 L","3 R","5 RL"]
result = count_magic_parents(instructions)
print(result) # Output will be the number of magic parents

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!