Skip to main content

Check if all leaf nodes are at same level in scala

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

/* 
  Scala program for
  Check if all leaves are at same level 
*/
// Binary Tree Node
class TreeNode(var data: Int,
	var left: TreeNode,
		var right: TreeNode)
{
	def this(data: Int)
	{
		// Set node value
		this(data, null, null);
	}
}
class BinaryTree(var root: TreeNode,
	var depth: Int)
{
	def this()
	{
		this(null, -1);
	}
	def 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
				checkLeafHeight(node.left, level + 1);
				checkLeafHeight(node.right, level + 1);
			}
		}
	}
	def 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");
		}
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
		// Create new tree
		var tree: BinaryTree = 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();
		// Add new node
		tree.root.left.left.left = new TreeNode(7);
		/*
		   When add new node
		    -----------------------
		          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.

New Comment