Category Archives: Trees

Print cousins of a given node in Binary Tree

Given a binary tree and a node, print all cousins of given node. Note that siblings should not be printed. Example: Input : root of below tree 1 / \ 2 3 / \ / \ 4 5 6 7 and pointer to a node say 5. Output : 6, 7 We strongly recommend you… Read More »

Iterative function to check if two trees are identical

Two trees are identical when they have same data and arrangement of data is also same. To identify if two trees are identical, we need to traverse both trees simultaneously, and while traversing we need to compare data and children of the trees. Examples: Input : Roots of below trees 10 10 / \ /… Read More »

Check if two trees are Mirror

Given two Binary Trees, write a function that returns true if two trees are mirror of each other, else false. For example, the function should return true for following input trees. We strongly recommend that you click here and practice it, before moving on to the solution. This problem is different from the problem discussed… Read More »

Create a Doubly Linked List from a Ternary Tree

Given a ternary tree, create a doubly linked list out of it. A ternary tree is just like binary tree but instead of having two nodes, it has three nodes i.e. left, middle, right. The doubly linked list should holds following properties – Left pointer of ternary tree should act as prev pointer of doubly… Read More »

Print Binary Tree in 2-Dimensions

Given a Binary Tree, print it in two dimension. Examples: Input : Pointer to root of below tree 1 / \ 2 3 / \ / \ 4 5 6 7 Output : 7 3 6 1 5 2 4 We strongly recommend you to minimize your browser and try this yourself first. If we… Read More »

Sink Odd nodes in Binary Tree

Given a Binary Tree having odd and even elements, sink all its odd valued nodes such that no node with odd value could be parent of node with even value. There can be multiple outputs for a given tree, we need to print one of them. It is always possible to convert a tree (Note… Read More »

Number of ways to traverse an N-ary tree

Given an n-ary tree, count number of ways to traverse an n-ary (or a Directed Acyclic Graph) tree starting from the root vertex. Suppose we have a given N-ary tree as shown below. Now we have to find the number of ways of traversing the whole tree starting from the root vertex. There can be… Read More »

Density of Binary Tree in One Traversal

Given a Binary Tree, find density of it by doing one traversal of it. Density of Binary Tree = Size / Height Examples: Input: Root of following tree 10 / \ 20 30 Output: 1.5 Height of given tree = 2 Size of given tree = 3 Input: Root of following tree 10 / 20… Read More »