-
Notifications
You must be signed in to change notification settings - Fork 163
Expand file tree
/
Copy pathAncestorMatx.java
More file actions
96 lines (79 loc) · 2.72 KB
/
AncestorMatx.java
File metadata and controls
96 lines (79 loc) · 2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// Java Program to construct ancestor matrix for a given tree
import java.util.*;
class AncestorMatx
{
// ancestorMatrix function to populate the matrix of
public static void ancestorMatrix(Node root ,int matrix[][],int size)
{
// base case:
if (root==null)
return ;
// call recursively for a preorder {left}
ancestorMatrix(root.left, matrix, size);
// call recursively for preorder {right}
ancestorMatrix(root.right, matrix, size);
// here we will reach the root node automatically
// try solving on pen and paper
if (root.left != null)
{
// make the current node as parent of its children node
matrix[root.data][root.left.data] = 1;
// iterate through all the columns of children node
// all nodes which are children to
// children of root node will also
// be children of root node
for (int i = 0; i < size; i++)
{
// if children of root node is a parent
// of someone (i.e 1) then make that node
// as children of root also
if (matrix[root.left.data][i] == 1)
matrix[root.data][i] = 1;
}
}
// same procedure followed for right node as well
if (root.right != null)
{
matrix[root.data][root.right.data] = 1;
for (int i = 0; i < size; i++)
{
if (matrix[root.right.data][i]==1)
matrix[root.data][i] = 1;
}
}
}
// Driver program to test the program
public static void main(String[] args)
{
// construct the binary tree as follows
Node tree_root = new Node(5);
tree_root.left = new Node (1);
tree_root.right = new Node(2);
tree_root.left.left = new Node(0);
tree_root.left.right = new Node(4);
tree_root.right.left = new Node(3);
// size of matrix
int size = 6;
int matrix [][] = new int[size][size];
ancestorMatrix(tree_root, matrix, size);
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
System.out.print(matrix[i][j]+" ");
}
System.out.println();
}
}
// node class for tree node
static class Node
{
public int data ;
public Node left ,right;
public Node (int data)
{
this.data = data;
this.left = this.right = null;
}
}
}