Close

Counting the number of leaf nodes in a binary tree

Given a binary tree, write a program to count the number of leaf nodes. A leaf node is a node which does not have left and right children.For example consider the following binary tree. It has 3 leaf nodes namely 1, 4 and 7. The solution is simple. The number of leaf nodes of a…

Check if two binary trees are identical

Given two binary tress, how do we check if they are identical in structure, and  contents? For example the following two binary trees are identical. We can solve this problem using recursion effectively. The function checks if the root element is equal and use the same function to check if it’s left and right sub-trees…

Level order traversal of a binary tree

Given a binary tree, we have to print the data level wise.  For example level order traversal of the following tree produces the sequence 5,3,8,2,4,6,1,7. The hint to solve this problem is to use a Queue data structure. We start by inserting the root node into the queue. Until the queue is empty, we remove…

Traversals of a binary tree

Traversal algorithms of non-linear data structures like trees are designed to visit/print all the elements in that structure. There are three main traversals of the binary tree. Namely In-order traversal Post-order traversal Pre-order traversal In addition to these, there are inverses of the above algorithms, and there is a level order traversal. In this post…