Input:
Root = 0
/\ 1 2
Output:
Ancestor Matrix:
[0 1 1][0 0 0][0 0 0] Explanation:
- Node 0 is the ancestor of both 1 and 2, so `mat[0][1]= 1` and `mat[0][2]= 1`.
- Nodes 1 and 2 are leaf nodes and do not have descendants, so their rows are all zeros.
classSolution:
defconstructAncestorMatrix(self, root, n):
# Initialise matrix and an empty ancestor list matrix = [[0for _ in range(n)] for _ in range(n)]
self.dfs(root, matrix, [])
return matrix
defdfs(self, node, matrix, ancestors):
ifnot node:
return# Mark current node's ancestors in the matrixfor ancestor in ancestors:
matrix[ancestor][node.val] =1# Add current node to the ancestors list and recurse ancestors.append(node.val)
self.dfs(node.left, matrix, ancestors)
self.dfs(node.right, matrix, ancestors)
# Remove current node from ancestors list (backtracking) ancestors.pop()
# Example usageif __name__ =="__main__":
root = TreeNode(0)
root.left = TreeNode(1)
root.right = TreeNode(2)
root.right.left = TreeNode(3)
root.right.right = TreeNode(4)
solution = Solution()
n =5 ancestor_matrix = solution.constructAncestorMatrix(root, n)
for row in ancestor_matrix:
print(row)
⏰ Time complexity: O(n^2). Each row requires traversal of the subtree, and marking ancestors for all nodes can approach a quadratic complexity depending on the shape of the binary tree.
🧺 Space complexity: O(n). For recursive calls (stack space) or tracking ancestors at any point.