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

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

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

#  Binary Tree node
class TreeNode
# Define the accessor and reader of class TreeNode
attr_accessor :data, :left, :right
def initialize(data)
#  Set node value
self.data = data
self.left = nil
self.right = nil
end
end

class BinaryTree
# Define the accessor and reader of class BinaryTree
attr_accessor :root
def initialize()
self.root = nil
end

#  Display pre order elements
def preorder(node)
if (node != nil)
#  Print node value
print("  ", node.data)
self.preorder(node.left)
self.preorder(node.right)
end

end

#  Returns the Sum of all the right leaves in binary tree
def rightLeavesSum(node)
sum = 0
if (node != nil)
if (node.right != nil &&
node.right.left == nil &&
node.right.right == nil)
#  When get right leaf node
sum = node.right.data
end

#  Recursively visit left and right subtree.
#  And find sum of right leaf nodes
sum = sum + self.rightLeavesSum(node.left) +
self.rightLeavesSum(node.right)
end
return sum
end
end

def main()
#  New binary tree
tree = BinaryTree.new()
#    Constructor binary tree
#    -----------------------
#          6
#         / \
#        /   \
#       /     \
#      2       3
#     / \       \
#    8   10      1
#       /  \    / \
#      6   -2  4   5
tree.root = TreeNode.new(6)
tree.root.left = TreeNode.new(2)
tree.root.left.left = TreeNode.new(8)
tree.root.left.right = TreeNode.new(10)
tree.root.left.right.right = TreeNode.new(-2)
tree.root.left.right.left = TreeNode.new(6)
tree.root.right = TreeNode.new(3)
tree.root.right.right = TreeNode.new(1)
tree.root.right.right.left = TreeNode.new(4)
tree.root.right.right.right = TreeNode.new(5)
print("\n Tree Nodes : ")
tree.preorder(tree.root)
#  Find right leaf sum
sum = tree.rightLeavesSum(tree.root)
#  Display result
print("\n Right leaves nodes sum : ", sum)
end

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.