Wednesday, 26 November 2014

There is a binary tree of size N. All nodes are numbered between 1-N(inclusive). There is a N*N integer matrix Arr[N][N], all elements are initialized to zero. So for all the nodes A and B, put Arr[A][B] = 1 if A is an ancestor of B (NOT just the immediate ancestor).

Problem:
There is a binary tree of size N. All nodes are numbered between 1-N(inclusive). There is a N*N integer matrix Arr[N][N], all elements are initialized to zero. So for all the nodes A and B, put Arr[A][B] = 1 if A is an ancestor of B (NOT just the immediate ancestor).

Solution:

The below solution is O(n^2) solution. Each array entry is visited exactly once.

The basic idea is to make current node ancestor for all the nodes except for itself and it's own ancestors.

For any node, it's own ancestors  are maintained in set.
Pseudo code:

void fill(int[][] a,int n, Node root,Set<Integer> parents) {
     if(root == null)return;
     for(int j=0;j<n;j++) {
        if(!parents.contains(j) && j != root.value) {
                  a[root.value][j] = 1;
        }
     }
     parents.add(root.value);
     fill(a,n,root.left,parents);
     fill(a,n,root.right,parents);
     parents.remove(root.value);
}

1 comment:

  1. Wrong solution. Lets take binary heap(tree) containing 3 elements 1 2 3. Then the result matrix it would be as matrix[2][3]=1. Which is wrong since 3 is not ancestor of 2 or vice versa.

    ReplyDelete