Sum of all the grandchild nodes of binary tree in kotlin

Kotlin program for Sum of all the grandchild nodes of binary tree. Here mentioned other language solution.
/*
Kotlin program for
Sum of nodes in binary tree whose grandparents exists
*/
// Binary Tree node
class TreeNode
{
var data: Int;
var left: TreeNode ? ;
var right: TreeNode ? ;
constructor(data: Int)
{
// Set node value
this.data = data;
this.left = null;
this.right = null;
}
}
class BinaryTree
{
var root: TreeNode ? ;
constructor()
{
this.root = null;
}
fun preOrder(node: TreeNode ? ): Unit
{
if (node != null)
{
// Print node value
print(" " + node.data);
// Visit left subtree
this.preOrder(node.left);
// Visit right subtree
this.preOrder(node.right);
}
}
fun grandchildSum(node: TreeNode ? , level : Int): Int
{
if (node != null)
{
var result: Int = 0;
if (level > 2)
{
// Get the node
result = node.data;
}
// Visit left subtree and right subtree
return result +
this.grandchildSum(node.left, level + 1) +
this.grandchildSum(node.right, level + 1);
}
else
{
return 0;
}
}
}
fun main(args: Array < String > ): Unit
{
// Create new binary trees
val tree: BinaryTree = BinaryTree();
/*
4
/ \
/ \
12 7
/ \ \
2 3 1
/ \ /
6 8 5
/
9
----------------
Constructing binary tree
*/
// Add nodes
tree.root = TreeNode(4);
tree.root?.left = TreeNode(12);
tree.root?.left?.right = TreeNode(3);
tree.root?.left?.right?.left = TreeNode(6);
tree.root?.left?.right?.left?.left = TreeNode(9);
tree.root?.left?.right?.right = TreeNode(8);
tree.root?.left?.left = TreeNode(2);
tree.root?.right = TreeNode(7);
tree.root?.right?.right = TreeNode(1);
tree.root?.right?.right?.left = TreeNode(5);
// Display tree node
print("\n Tree Nodes ");
tree.preOrder(tree.root);
// Find node sum
// 2 + 3 + 6 + 9 + 8 + 1 + 5 = 34
val result: Int = tree.grandchildSum(tree.root, 1);
// Display result
println("\n Result : " + result);
}
Output
Tree Nodes 4 12 2 3 6 9 8 7 1 5
Result : 34
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