Category Archives: Trees

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 »

Print root to leaf paths without using recursion

Given a binary tree, print all its root to leaf paths without using recursion. For example, consider the following Binary Tree. 6 / \ 3 5 / \ \ 2 5 4 / \ 7 4 There are 4 leaves, hence 4 root to leaf paths – 6->3->2 6->3->5->7 6->3->5->4 6->5>4 We strongly recommend you… 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 The idea is to use map. We use… Read More »

Convert a normal BST to Balanced BST

Given a BST (Binary Search Tree) that may be unbalanced, convert it into a balanced BST that has minimum possible height. Examples : Input: 30 / 20 / 10 Output: 20 / \ 10 30 Input: 4 / 3 / 2 / 1 Output: 3 3 2 / \ / \ / \ 1 4… Read More »