# Sum of all right leaf nodes of binary tree in python

Python program for Sum of all right leaf nodes of binary tree. Here mentioned other language solution.

``````#    Python 3 program for
#    Sum of all right leaves nodes in a binary tree
#    Using recursion

#  Binary Tree node
class TreeNode :
def __init__(self, data) :
#  Set node value
self.data = data
self.left = None
self.right = None
class BinaryTree :
def __init__(self) :
#  Set initial tree root
self.root = None
#  Display pre order elements
def preorder(self, node) :
if (node != None) :
#  Print node value
print("",node.data, end =" ")
self.preorder(node.left)
self.preorder(node.right)
#  Returns the Sum of all the right leaves in binary tree
def  rightLeavesSum(self, node) :
sum = 0
if (node != None) :
if (node.right != None and
node.right.left == None and
node.right.right == None) :
#  When get right leaf node
sum = node.right.data
#  Recursively visit left and right subtree.
#  And find sum of right leaf nodes
sum = sum + self.rightLeavesSum(node.left) + \
self.rightLeavesSum(node.right)
return  sum
def main() :
#  New binary tree
tree = BinaryTree()
#    Constructor binary tree
#    -----------------------
#          6
#         / \
#        /   \
#       /     \
#      2       3
#     / \       \
#    8   10      1
#       /  \    / \
#      6   -2  4   5
tree.root = TreeNode(6)
tree.root.left = TreeNode(2)
tree.root.left.left = TreeNode(8)
tree.root.left.right = TreeNode(10)
tree.root.left.right.right = TreeNode(-2)
tree.root.left.right.left = TreeNode(6)
tree.root.right = TreeNode(3)
tree.root.right.right = TreeNode(1)
tree.root.right.right.left = TreeNode(4)
tree.root.right.right.right = TreeNode(5)
print("\n Tree Nodes : ", end ="")
tree.preorder(tree.root)
#  Find right leaf sum
sum = tree.rightLeavesSum(tree.root)
#  Display result
print("\n Right leaves nodes sum :",sum)

if __name__=="__main__":
main()``````

Output

`````` Tree Nodes :  6  2  8  10  6  -2  3  1  4  5
Right leaves nodes sum : 3``````

## Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.