![]() |
VOOZH | about |
Given an ancestor matrix mat[n][n] where the Ancestor matrix is defined as below.
Construct a Binary Tree from a given ancestor matrix where all its values of nodes are from 0 to n-1.
Examples:
Input: mat[][] = {{0, 1, 1},
{0, 0, 0},
{0, 0, 0}};Output: There are different possible outputs because ancestor matrix doesn’t store that which child is left and which is right, one of the ouput is shown below.
👁 Construct-Binary-Tree-from-Ancestor-Matrix-46
Input: mat[][] = { {0, 0, 0, 0, 0, 0},
{1, 0, 0, 0, 1, 0},
{0, 0, 0, 1, 0,,0},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0},
{1, 1, 1, 1, 1, 0} }Output: There are different possible outputs because ancestor matrix doesn’t store that which child is left and which is right, one of the ouput is shown below.
👁 Construct-Binary-Tree-from-Ancestor-Matrix-47
Approach:
The idea is to store the number of successor nodes for each node. Starting from the root value (which will be ancestor for all nodes), create the corresponding node and set sum value to -1. Then iterate through all its successor values and find the index with with maximum successor nodes. If index is not -1, then create the left node recursively using this index. Similarly, again iterate through the successor nodes and again find the index with maximum successor nodes. If this index is not -1, then use this index to recursively create the right subtree.
Below is the implementation of the above approach:
0 1 4 5 3 2
Time Complexity: O(n^2), where n is the size of the binary tree.
Auxiliary Space: O(n)
Please refer to this article for Bottom-Up approach: Construct tree from ancestor matrix.