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

Csharp program for Sum of all right leaf nodes of binary tree. Here mentioned other language solution.
// Include namespace system
using System;
/*
Csharp program for
Sum of all right leaves nodes in a binary tree
Using recursion
*/
// Binary Tree node
public class TreeNode
{
public int data;
public TreeNode left;
public TreeNode right;
public TreeNode(int data)
{
// Set node value
this.data = data;
this.left = null;
this.right = null;
}
}
public class BinaryTree
{
public TreeNode root;
public BinaryTree()
{
// Set initial tree root
this.root = null;
}
// Display pre order elements
public void preorder(TreeNode node)
{
if (node != null)
{
// Print node value
Console.Write(" " + node.data);
this.preorder(node.left);
this.preorder(node.right);
}
}
// Returns the Sum of all the right leaves in binary tree
public int rightLeavesSum(TreeNode node)
{
var sum = 0;
if (node != null)
{
if (node.right != null &&
node.right.left == null &&
node.right.right == null)
{
// When get right leaf node
sum = node.right.data;
}
// Recursively visit left and right subtree.
// And find sum of right leaf nodes
sum = sum + this.rightLeavesSum(node.left) +
this.rightLeavesSum(node.right);
}
return sum;
}
public static void Main(String[] args)
{
// New binary tree
var tree = new BinaryTree();
/*
Constructor binary tree
-----------------------
6
/ \
/ \
/ \
2 3
/ \ \
8 10 1
/ \ / \
6 -2 4 5
*/
// Add tree node
tree.root = new TreeNode(6);
tree.root.left = new TreeNode(2);
tree.root.left.left = new TreeNode(8);
tree.root.left.right = new TreeNode(10);
tree.root.left.right.right = new TreeNode(-2);
tree.root.left.right.left = new TreeNode(6);
tree.root.right = new TreeNode(3);
tree.root.right.right = new TreeNode(1);
tree.root.right.right.left = new TreeNode(4);
tree.root.right.right.right = new TreeNode(5);
Console.Write("\n Tree Nodes : ");
tree.preorder(tree.root);
// Find right leaf sum
var sum = tree.rightLeavesSum(tree.root);
// Display result
Console.Write("\n Right leaves nodes sum : " + sum);
}
}
Output
Tree Nodes : 6 2 8 10 6 -2 3 1 4 5
Right leaves nodes sum : 3
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.
New Comment