Category Archives: Trees

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 »

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 »

Non-recursive program to delete an entire binary tree.

We have discussed recursive implementation to delete an entire binary tree here. We strongly recommend you to minimize your browser and try this yourself first. Now how to delete an entire tree without using recursion. This could easily be done with the help of Level Order Tree Traversal. The idea is for each dequeued node from the… Read More »

Diagonal Traversal of Binary Tree

Consider lines of slope -1 passing between nodes. Given a Binary Tree, print all diagonal elements in a binary tree belonging to same line. Input : Root of below tree Output : Diagonal Traversal of binary tree : 8 10 14 3 6 7 13 1 4 We strongly recommend you to minimize your browser… Read More »

Construct tree from ancestor matrix

Given an ancestor matrix mat[n][n] where Ancestor matrix is defined as below. mat[i][j] = 1 if i is ancestor of j mat[i][j] = 0, otherwise Construct a Binary Tree from given ancestor matrix where all its values of nodes are from 0 to n-1. It may be assumed that the input provided the program is… Read More »