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

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

``````/*
TypeScript program for
Check if all leaves are at same level
*/
// Binary Tree Node
class TreeNode
{
public data: number;
public left: TreeNode;
public right: TreeNode;
constructor(data: number)
{
// Set node value
this.data = data;
this.left = null;
this.right = null;
}
}
class BinaryTree
{
public root: TreeNode;
public depth: number;
constructor()
{
// Set initial tree root
this.root = null;
this.depth = -1;
}
public checkLeafHeight(node: TreeNode, level: number)
{
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);
}
}
}
public isSameLevelLeaf()
{
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
console.log("No");
}
else
{
// When leaf node is same level
console.log("Yes");
}
}
public static main(args: string[])
{
// Create new tree
var tree = new BinaryTree();
/*
Make A Binary Tree
--------------------
1
/  \
2    3
/    /  \
4    5    6

*/
//insertion of binary Tree nodes
tree.root = new TreeNode(1);
tree.root.left = new TreeNode(2);
tree.root.right = new TreeNode(3);
tree.root.right.right = new TreeNode(6);
tree.root.right.left = new TreeNode(5);
tree.root.left.left = new TreeNode(4);
tree.isSameLevelLeaf();
tree.root.left.left.left = new TreeNode(7);
/*
-----------------------
1
/  \
2    3
/    /  \
4    5    6
/
7
*/
tree.isSameLevelLeaf();
}
}
BinaryTree.main([]);
/*
file : code.ts
tsc --target es6 code.ts
node code.js
*/``````

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.