Check if a binary tree has all leaf nodes at same level

Posted by on Mar 31, 2024

A binary tree is given, the task is to check if all it's leaf nodes are at same level or not.


Solutions

Method 1: Recursion

We have two variables "leafLevel = -1" and "diff = 0", "leafLevel" will hold the level of very first leaf node.

We will traverse the tree in "level-order" passing current level in each recur, the idea is to check if other leaf nodes have same level as the first leaf (leafLevel); if not increase "diff".

In the end check if value of "diff" is changed, if yes that means leaf nodes are at different levels.

Complexity

The time complexity of this solution is O(n) and space complexity is O(n) due to call stack.

Related


Print Nodes in Top View of a Binary Tree

Print/Traverse a Binary Tree in Zigzag Order

Level Order or Breadth First traversal of Binary Tree

Print diagonal traversal of a binary tree

Find the diameter or width of a binary tree

In-order Tree Traversal - Iterative and Recursive

Create a mirror tree from a given binary tree

Write a program to print height/depth of a Binary Tree

Print the left view of a binary tree

Pre-order Tree Traversal - Iterative and Recursive

Print a Binary Tree in Vertical Order