Where I am doing mistake ??
Print all nodes at distance K
2 test cases are failing ??
okay i will check and get back to you with the errors.
Hi as seen in your code you are taking k distance downward from the target node i.e all nodes which are present at k distance below the target node. However there can be nodes present in the parent hierarchy (above) the target node as well.
The fix to this pretty simple. you must have observed that the question does not give the tree directly but its preorder and inorder so that we can create the tree. This is done so that we can create a custom tree where each node also has pointer to its parent node. After this it just becomes a 3-way recursive search (top,left , right) of the kth node.
Please help me to correct code
your new node class should be like
class Node {
int data;
Node left;
Node right;
Node parent;
}
next create an arraylist of integers which will store the data of all the nodes present at k distance.
Finally create a bfs type of function that searches in all directions for the kth node from target.