Category Archives: Trees

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 »

BFS vs DFS for Binary Tree

What are BFS and DFS for Binary Tree? A Tree is typically traversed in two ways: Breadth First Traversal (Or Level Order Traversal) Depth First Traversals Inorder Traversal (Left-Root-Right) Preorder Traversal (Root-Left-Right) Postorder Traversal (Left-Right-Root) BFS and DFSs of above Tree Breadth First Traversal : 1 2 3 4 5 Depth First Traversals: Preorder Traversal… Read More »

Check if leaf traversal of two Binary Trees is same?

Leaf traversal is sequence of leaves traversed from left to right. The problem is to check if leaf traversals of two given Binary Trees are same or not. Expected time complexity O(n). Expected auxiliary space O(h1 + h2) where h1 and h2 are heights of two Binary Trees. Examples: Input: Roots of below Binary Trees… Read More »