Saturday, February 16, 2013

Build Binary Tree From Matrix



/*
 * Question:
   Create the n-ary tree from the ancestor matrix.
   matrix[i][j] = 1 if i is the ancestor of j.
 *
 * Solution:
 * (Curent solution provides solution for building BST from matrix.  Any type of tree can be build using  
    same logic)
 *
 * if j is the root element then matrix[i][j] = 0 for all elements in column j, as j as not ancestor.
 * So find the column in matrix with all elements in that column as 0.
 *
 * Once we find the root.  Iterate recursively through each row to find its children. e.g. if j is the root
 * then matrix with row j will contain all children of the node j.
 *
 * Runtime: O(n*n).
 * Space time: O(n*n). (To create tree)
 *
 */

public class BuildBSTFromMatrix {

public static class Node {
public Node left;
public Node right;
public int value;
}


Node createTree(int[][] arr, int dim, Node root) {

for(int i=0; i if(arr[root.value][i] == 1) {
Node newNode = new Node();
newNode.value = i;
createTree(arr, dim, newNode);

if(root.value > i)
root.left = newNode;
else
root.right = newNode;
}
}

return root;
}


Node createTreeFromMatrix(int[][] arr, int dim) {

Node root = new Node();

for(int i=0; i
boolean flag = true;

for(int j=0; j if(arr[j][i] == 1) {
flag = false;
break;
}
}

if(flag == true) {
root.value = i;
break;
}
}

root = createTree(arr, dim, root);

return root;
}

void inOrderTraversal(Node root) {

if(root != null) {
inOrderTraversal(root.left);
System.out.print(root.value+" ");
inOrderTraversal(root.right);
}
}

public static void main(String args[]) {

int[][] arr = new int[7][7];
int dim = 7;

arr[1][0] = 1;
arr[1][2] = 1;
arr[3][1] = 1;
arr[3][5] = 1;
arr[2][4] = 1;
arr[5][4] = 1;
arr[5][6] = 1;

Node root = new BuildBSTFromMatrix().createTreeFromMatrix(arr, dim);
new BuildBSTFromMatrix().inOrderTraversal(root);

}
}


No comments: