# Check if all leaf nodes are at same level in kotlin

Kotlin program for Check if all leaf nodes are at same level. Here problem description and other solutions.

``````/*
Kotlin program for
Check if all leaves are at same level
*/

// 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 ? ;
var depth: Int;
constructor()
{
this.root = null;
this.depth = -1;
}
fun checkLeafHeight(node: TreeNode ? , level : Int): Unit
{
if (node != null)
{
// Test node is leaf or not
if (node.left == null && node.right == null)
{
if (this.depth == -1)
{
// This is first leaf node
// Get node level
this.depth = level;
}
else if (this.depth != level)
{
// When two leaf nodes is different level
this.depth = -2;
return;
}
}
if (this.depth != -2)
{
// Recursively visit left and right subtree
this.checkLeafHeight(node.left, level + 1);
this.checkLeafHeight(node.right, level + 1);
}
}
}
fun isSameLevelLeaf(): Unit
{
this.depth = -1;
// Test
this.checkLeafHeight(this.root, 1);
// Display result
if (this.depth < 0)
{
// Two possible case
// 1) When tree empty
// 2) When leaf node are not same level
println("No");
}
else
{
// When leaf node is same level
println("Yes");
}
}
}
fun main(args: Array < String > ): Unit
{
// Create new tree
val tree: BinaryTree = BinaryTree();
/*
Make A Binary Tree
--------------------
1
/  \
2    3
/    /  \
4    5    6

*/
//insertion of binary Tree nodes
tree.root = TreeNode(1);
tree.root?.left = TreeNode(2);
tree.root?.right = TreeNode(3);
tree.root?.right?.right = TreeNode(6);
tree.root?.right?.left = TreeNode(5);
tree.root?.left?.left = TreeNode(4);
tree.isSameLevelLeaf();
tree.root?.left?.left?.left = TreeNode(7);
/*
-----------------------
1
/  \
2    3
/    /  \
4    5    6
/
7
*/
tree.isSameLevelLeaf();
}``````

Output

``````Yes
No``````

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