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 is always the Root node
Input format:
The nodenumber stringrepresenting the relative position of the node wrt root node,ie node
Eg:
This is representing a tree having a root node as and is the left child of node and is the right child of node and is the left child of node
L
R
RL
SOLUTION
class TreeNode:
def initself val:
self.val val
self.left None
self.right None
def buildtreeinstructions:
nodes : TreeNode # Root node
for instruction in instructions:
nodeval, path instruction.split
nodeval intnodeval
current nodes # Start from root
# Traverse the path to insert the node in correct position
for direction in path:: # 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 pathL:
current.left TreeNodenodeval
elif pathR:
current.right TreeNodenodeval
# Save the node for further use
nodesnodeval current.left if pathL else current.right
return nodes
def countsubtreenodesnode:
if node is None:
return
# Recursively count nodes in left and right subtrees
leftcount countsubtreenodesnodeleft
rightcount countsubtreenodesnoderight
# Check if the current node is a magic parent
if node.left is not None and node.right is not None:
if leftcount and rightcount or leftcount and rightcount :
countsubtreenodes.magicparents
# Return total nodes in the subtree rooted at current node
return leftcount rightcount
def countmagicparentsinstructions:
# Build the tree from input instructions
root buildtreeinstructions
# Initialize a variable to count magic parents
countsubtreenodes.magicparents
# Count the number of nodes in subtrees and check for magic parents
countsubtreenodesroot
return countsubtreenodes.magicparents
# Input example:
instructions L R RL
result countmagicparentsinstructions
printresult # 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
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
