I need to print the ancestors of a node in binary tree. e.g Node 7 has ancestors as 1,3 . I have written the below code but output is coming as 7. Can you suggest the issues in this code?
1
/ \
2 3
/ \ / \
4 5 6 7
public static String findAncestor(BinaryTreeNode root , int number, boolean matched) {
if (root != null) {
int rootData = root.getData();
BinaryTreeNode left = root.getLeft();
BinaryTreeNode right = root.getRight();
if (left != null && right != null) {
return findAncestor (root.getLeft(), number, matched ) + findAncestor (root.getRight(), number, matched);
}
if (left != null) {
return findAncestor (root.getLeft(), number, matched ) ;
}
if (right != null) {
return findAncestor (root.getRight(), number, matched ) ;
}
if (rootData == number) {
matched = true;
return String.valueOf(rootData);
}
if (matched) {
return String.valueOf(rootData);
}
}
return "";
}