# Sum of alternate leaf nodes in bst in scala

Scala program for Sum of alternate leaf nodes in bst. Here mentioned other language solution.

``````// Scala program for
// Sum of alternate leaf nodes in bst
class TreeNode(var data: Int,
var left: TreeNode,
var right: TreeNode)
{
def this(data: Int)
{
this(data, null, null);
}
}
class BinarySearchTree(var root: TreeNode,
var alternate: Boolean)
{
def this()
{
this(null, false);
}
// Insert a new node element
def addNode(data: Int): Unit = {
// Create a new node
var node: TreeNode = new TreeNode(data);
if (this.root == null)
{
// When add first node in bst
this.root = node;
}
else
{
var find: TreeNode = this.root;
// Add new node to proper position
while (find != null)
{
if (find.data >= data)
{
if (find.left == null)
{
// When left child empty
// So add new node here
find.left = node;
return;
}
else
{
// Otherwise
// Visit to left sub-tree
find = find.left;
}
}
else
{
if (find.right == null)
{
// When right child empty
// So add new node here.
find.right = node;
return;
}
else
{
// Visit to right sub-tree
find = find.right;
}
}
}
}
}
def leafSum(node: TreeNode): Int = {
if (node != null)
{
if (node.left == null &&
node.right == null)
{
// Case A
// When node is leaf node.
// Change status.
this.alternate = !this.alternate;
// Check node is alternate or not.
if (this.alternate)
{
// When get alternate node.
return node.data;
}
}
else
{
// Case B
// When node is internal
// Visit left and right subtree and
// Find alternate node.
return leafSum(node.left) +
leafSum(node.right);
}
}
return 0;
}
def alternateLeafSum(): Int = {
// Reset alternate leaf node status
this.alternate = false;
return leafSum(this.root);
}
}
object Main
{
def main(args: Array[String]): Unit = {
var tree: BinarySearchTree = new BinarySearchTree();
/*
Binary search tree
-------------------
5
/  \
/    \
/      \
3        19
/ \     /   \
2   4   8     31
/ \    / \
7   15 25  50
*/
// Test
println(tree.alternateLeafSum());
}
}``````

Output

``34``

## 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.