GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

In binary tree return a matrix where mat(i,j) is 1 when i is an ancestor of .In place O(n)

Source :Amazon Interview Set 252 

I can fill this using post order traversal and putting ancestor nodes in stack.

In single traversal I can fill array for parents node.

But I am not able to figure out how all the ancestors list in matrix will be filled in single traversal and without extra space.

Please tell the algorithm for it.


asked Apr 10, 2016 by anonymous

2 Answers

I could think of a Pseudo-code below. It takes O(n) iterations (excluding the matrix write operations)


int matrix[][], ancestor[];
void Preorder(NODE root, int *count, int index)
          for(i = 0 to index -1)
              matrix[*count][ anc[i] ] = 1;
      ancestor[index] = *count;
      Preorder(root->left, count, index+1);
      Preorder(root->right, count, index+1);


answered Apr 10, 2016 by Sudhindra A

Simply traverse , and note that ancestors of parent are ancestor of child also, Have a look  

answered Apr 10, 2016 by kumar