Given a binary tree whose nodes are labeled from 0 to N-1, construct an N × N ancestor matrix. An ancestor matrix is a boolean matrix, whose cell (i, j) is true if i is an ancestor of j in the binary tree.

For example, consider the following binary tree:

Binary Tree

 
The output should be the following ancestor matrix

  0  0  0  0  0  0
  0  0  0  0  0  1
  0  0  0  0  0  0
  1  0  1  0  0  0
  1  1  1  1  0  1
  0  0  0  0  0  0

Practice this problem

The idea is to traverse the tree in a preorder fashion and keep track of ancestors in a container such as a set, a list, or an array. For each encountered node, mark its ancestors in the ancestor matrix using the ancestors’ container.

To keep the ancestors’ container updated, add the node to the ancestors’ list when it is visited and remove that node from the list of ancestors once its left and right subtrees are processed. Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

0 0 0 0 0 0
0 0 0 0 0 1
0 0 0 0 0 0
1 0 1 0 0 0
1 1 1 1 0 1
0 0 0 0 0 0

Java


Download  Run Code

Output:

[0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 1]
[0, 0, 0, 0, 0, 0]
[1, 0, 1, 0, 0, 0]
[1, 1, 1, 1, 0, 1]
[0, 0, 0, 0, 0, 0]

Python


Download  Run Code

Output:

[0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 1]
[0, 0, 0, 0, 0, 0]
[1, 0, 1, 0, 0, 0]
[1, 1, 1, 1, 0, 1]
[0, 0, 0, 0, 0, 0]

The time complexity of the above solution is O(N2) and requires O(N) extra space, where N is the size of the binary tree.