Algorithm:
Use a path array path[] to store current root to leaf path. Traverse from root to all leaves in top-down fashion. While traversing, store data of all nodes in current path in array path[]. When we reach a leaf node, print the path array.
Solution:
void
printPaths(Node node)
{
int
path[] =
new
int
[
1000
];
printPathsRecur(node, path,
0
);
}
void
printPathsRecur(Node node,
int
path[],
int
pathLen)
{
if
(node ==
null
)
return
;
path[pathLen] = node.data;
pathLen++;
if
(node.left ==
null
&& node.right ==
null
)
printArray(path, pathLen);
else
{
printPathsRecur(node.left, path, pathLen);
printPathsRecur(node.right, path, pathLen);
}
}
void
printArray(
int
ints[],
int
len)
{
int
i;
for
(i =
0
; i < len; i++)
{
System.out.print(ints[i] +
" "
);
}
System.out.println(
""
);
}
No comments:
Post a Comment