# Python3 program for the above approach
# Structure of Binary Tree
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function to create a new node
def newnode(data):
temp = Node(data)
# Return the created node
return temp
# Function to insert a node in the tree
def insert(s, i, N, root, temp):
if (i == N):
return temp
# Left insertion
if (s[i] == 'L'):
root.left = insert(s, i + 1, N,
root.left, temp)
# Right insertion
else:
root.right = insert(s, i + 1, N,
root.right, temp)
# Return the root node
return root
# Function to find sum of specially
# balanced nodes in the Tree
def SBTUtil(root, sum):
# Base Case
if (root == None):
return [0, sum]
if (root.left == None and
root.right == None):
return [root.data, sum]
# Find the left subtree sum
left, sum = SBTUtil(root.left, sum)
# Find the right subtree sum
right, sum = SBTUtil(root.right, sum)
# Condition of specially
# balanced node
if (root.left and root.right):
# Condition of specially
# balanced node
if ((left % 2 == 0 and
right % 2 != 0) or
(left % 2 != 0 and
right % 2 == 0)):
sum += root.data
# Return the sum
return [left + right + root.data, sum]
# Function to build the binary tree
def build_tree(R, N, str, values):
# Form root node of the tree
root = newnode(R)
# Insert nodes into tree
for i in range(0, N - 1):
s = str[i]
x = values[i]
# Create a new Node
temp = newnode(x)
# Insert the node
root = insert(s, 0, len(s),
root, temp)
# Return the root of the Tree
return root
# Function to find the sum of specially
# balanced nodes
def speciallyBalancedNodes(R, N, str, values):
# Build Tree
root = build_tree(R, N, str, values)
# Stores the sum of specially
# balanced node
sum = 0
# Function Call
tmp, sum = SBTUtil(root, sum)
# Print required sum
print(sum, end = ' ')
# Driver code
if __name__ == "__main__":
# Given nodes
N = 7
# Given root
R = 12
# Given path info of nodes
# from root
str = [ "L", "R", "RL",
"RR", "RLL", "RLR" ]
# Given node values
values = [ 17, 16, 4, 9, 2, 3 ]
# Function Call
speciallyBalancedNodes(R, N, str,
values)
# This code is contributed by rutvik_56