Category Archives: Trees

View algorithms on Trees

Find the left view of a binary tree.

Question: Given the root pointer to a binary tree, find the left view of the tree. Input: Sample Tree (Pointer to node 1 is given). Output: 1, 2, 4 At a single glance of the problem, we can understand that we need to perform a level order traversal on the tree. This is similar to finding the number… Read More »

How many binary trees are possible with n nodes?

Question: How many binary trees are possible with n nodes? Input: Nodes = 3 Output: Answer = 5 For, example consider a tree with 3 nodes (n = 3), it will have a maximum combination of 5 different trees In general, if there are n nodes, there exist (2n)!/(n+1)! different trees.

Given a binary tree, construct its mirror tree.

Question: Given a binary tree, find its mirror tree. Input: A tree pointer is given. (Root pointer) Output: Pointer of mirrored tree. We can easily get the mirrored tree by a simple recursive algorithm. We traverse the tree and swap the left and right pointers. Time Complexity:- O(n) Space Complexity:- O(n) (due to recursive stack)

Find the height of the binary tree without using recursion.

Question: Given the root pointer to a binary tree, find the height. Input: Sample Tree (Pointer to node 1 is given). Output: 3 We discussed the recursive method to find the height of the binary tree in this post- Find the height of the binary tree The non-recursive method will definitely require the level order traversal technique. The… Read More »