[Expected Approach - 1] Using Pre-Order traversal and Ancestor Array - O(n^2) Time and O(n^2) Space
The idea is to traverse the tree. While traversing, keep track of ancestors in an array. When we visit a node, we add it to ancestor array and consider the corresponding row in the adjacency matrix. We mark all ancestors in its row as 1. Once a node and all its children are processed, we remove the node from ancestor array.
[Expected Approach - 2] Using Post-Order Traversal - O(n^2) Time and O(h) Space
The idea is to perform recursive traversal of the binary tree. For each node, process the left and right nodes. Set current node as ancestor of all nodes for which left and right nodes are ancestors. Then set current node as ancestor of left and right node.
Below is the implementation of the above approach: