A* search algorithm infinite loop - algorithm

Like the title says, This A* search algorithm never stops searching. I'm trying to create a working A* search algorithm for point-click walking in a 2D tile-based game, some tiles are walk-able and some tiles are solid.
PathFinder.java:
public class PathFinder {
public static List<Node> findPath(Map map, int sx, int sy, int dx, int dy) {
if(map.getTile(dx, dy).isSolid()) return null;
Node startNode = new Node(new Vector2i(sx, sy), null, 0, 0);
Vector2i goal = new Vector2i(dx, dy);
List<Node> open = new ArrayList<>();
HashSet<Node> closed = new HashSet<>();
open.add(startNode);
while(open.size() > 0) {
Node currentNode = open.get(0);
for(int i = 1; i < open.size(); i++) {
if(open.get(i).fCost < currentNode.fCost ||
open.get(i).fCost == currentNode.fCost && open.get(i).hCost < currentNode.hCost) {
currentNode = open.get(i);
}
}
open.remove(currentNode);
closed.add(currentNode);
if(currentNode.tile == goal){
System.out.println("returning path!");
return retracePath(startNode, currentNode);
}
for(Tile tile : map.getNeighbors(currentNode)) {
Vector2i neighbor = new Vector2i(tile.getTileX(), tile.getTileY());
if(tile.isSolid() || getNodeInHashSetForPosition(neighbor, closed) != null) {
continue;
}
double gCost = currentNode.gCost + getNodeDistance(currentNode.tile, neighbor);
if(currentNode.gCost < gCost || !vecInList(neighbor, open)) {
double hCost = getNodeDistance(neighbor, goal);
Node node = new Node(neighbor, currentNode, gCost, hCost);
if(!open.contains(node)) {
open.add(node);
}
}
}
}
return null;
}
private static List<Node> retracePath(Node startNode, Node endNode) {
List<Node> path = new ArrayList<>();
Node currentNode = endNode;
while(currentNode != startNode) {
path.add(currentNode);
currentNode = currentNode.parent;
}
List<Node> finalPath = new ArrayList<>();
for(int i = path.size() - 1; i > 0; i--) {
finalPath.add(path.get(i));
}
return finalPath;
}
private static boolean vecInList(Vector2i vec, List<Node> list) {
for(Node n : list) {
if(n.tile.equals(vec)) return true;
}
return false;
}
private static boolean vecInList(Vector2i vec, HashSet<Node> list) {
for(Node n : list) {
if(n.tile.equals(vec)) return true;
}
return false;
}
private static Node getNodeInHashSetForPosition(Vector2i position, HashSet<Node> hashSet) {
for(Node n : hashSet) {
if(n.tile.equals(position)) return n;
}
return null;
}
private static double getNodeDistance(Vector2i nodeA, Vector2i nodeB) {
int dstX = Math.abs(nodeA.x - nodeB.x);
int dstY = Math.abs(nodeA.y - nodeB.y);
if(dstX > dstY) return 14 * dstY + 10 * (dstX - dstY);
return (14 * dstX) + (10 * (dstY - dstX));
}
}
Node.java
public class Node {
public Vector2i tile;
public Node parent;
public double fCost, gCost, hCost; //a cost is like the distance it takes to get to that point. these are used to find the lowest cost way to get from start point A to end point B.
//gCost is the sum of all of our node to node, or tile to tile, distances.
//hCost is the direct distance from the start node to the end node.
//fCost is the total cost for all the ways we calculate to get to the end node/tile.
public Node(Vector2i tile, Node parent, double gCost, double hCost) { //NODE CONSTRUCTOR STARt
this.tile = tile;
this.parent = parent;
this.gCost = gCost;
this.hCost = hCost;
this.fCost = this.gCost + this.hCost;
}//NODE CONSTRUCTOR END
}

change the following:
if(!open.contains(node)) {
to:
if(!veckInList(neighbor, open) {

Related

Valid Binary Tree

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
static class ReturnData {
public boolean isBST;
public int max;
public int min;
public ReturnData(boolean is, int mi, int ma) {
isBST = is;
min = mi;
max = ma;
}
}
public boolean isValidBST(TreeNode root) {
if (root == null) {
return true;
}
ReturnData res = check(root);
if (res == null) {
return true;
}
return res.isBST;
}
private ReturnData check(TreeNode node) {
if (node == null) {
return null;
}
int min = node.val;
int max = node.val;
ReturnData left = check(node.left);
ReturnData right = check(node.right);
if (left != null) {
min = Math.min(min, left.min);
max = Math.max(max, left.max);
}
if (right != null) {
min = Math.min(min, right.min);
max = Math.max(max, right.max);
}
boolean isBST = true;
if (left != null && (!left.isBST || left.min >= node.val)) {
isBST = false;
}
if (right != null && (!right.isBST || right.min <= node.val)) {
isBST = false;
}
return new ReturnData(isBST, min, max);
}
}
I want to ask a LeetCode question, Question 98.
The question wants me to write an algorithm to check whether the given tree is a valid binary tree, so I wrote like this:
I create a constructor to initialize the return type, which contains the current node's value, max, and min value of its subtree.
I want to use recursion to check the validation.
But it doesn't work, I also check the solution but I still don't know why this way didn't work.
Hope someone could give me a hint, thanks.
The problem is in this condition:
left.min >= node.val
You'll want to see whether the maximum in the left tree exceeds the current node's value, so:
left.max >= node.val

Knight on Chess Board - Shortest Path

I'm trying to solve this problem: https://www.interviewbit.com/problems/knight-on-chess-board/#
Basically, you're given a board, a start point and an end point and have to find the shortest path. I'm trying to do BFS on the the board using the 8 possible moves a knight can make and returning the number of moves it took, or -1 if there was no solution. I'm getting a run time out of memory error. I'm not sure where the error (or potential errors) are occurring.
Edit: Previously I was getting an error because I forgot got to mark nodes as visited. I've added that in but I'm still not getting the right answer.
public class Solution {
private class Node {
int row;
int col;
int count;
public Node() {
this.row = 0;
this.col = 0;
this.count = 0;
}
public Node(int row, int col, int count) {
this.row = row;
this.col = col;
this.count = count;
}
}
public int knight(int A, int B, int sr, int sc, int er, int ec) {
int[][] matrix = new int[A][B];
Queue<Node> q = new LinkedList<>(); //linkedlist??
Node n = new Node(sr, sc, 0);
q.add(n);
matrix[sr][sc] = -1;
final int[][] SHIFTS = {
{-2,1},
{-2,-1},
{2,1},
{2,-1},
{-1,2},
{-1,-2},
{1,2},
{1,-2}
};
int count = 0;
while(!q.isEmpty()) {
Node cur = q.remove();
if(cur.row == er && cur.col == ec) {
return cur.count;
}
for(int[] i : SHIFTS) {
if(canTraverse(matrix, cur.row + i[0], cur.col + i[1])) {
matrix[cur.row + i[0]][cur.col + i[1]] = -1;
q.add(new Node(cur.row + i[0], cur.col + i[1], cur.count + 1));
}
}
}
return -1;
}
public static boolean canTraverse(int[][] matrix, int sr, int sc) {
if(sr < 0 || sr >= matrix.length || sc < 0 || sc >= matrix[sr].length || matrix[sr][sc] == -1) {
return false;
}
return true;
}
}
BFS algorithm needs to mark every visited position (node) to work properly. Else, such code could cause (almost certainly) runtime error or memory limit exceded (in short terms: A calls B and B calls A).
Solution: Create a boolean array and mark the nodes at the time they enter to the queue and you are done.

Maximum path length between two vertices in a DAG

Given a Directed Acyclic Graph, G and two vertices u and v, I need to find the longest u-v path in G. DFS calls explore function to store visited vertices in the visited[] boolean array (if vertex is visited the value in array is set true, otherwise it's false). Vertices u and v are never marked as visited. Variable MAX stores the max path; when STOP vertex is reached in explore() function MAX is set to max of current path length and MAX value. The code doesn't work right.
import java.util.Iterator;
import java.util.LinkedList;
public class DAG2 {
int vertex;
LinkedList<Integer> list[];
int START, STOP;
int length = 0;
int MAX = 0;
public DAG2(int vertex) {
this.vertex = vertex;
list = new LinkedList[vertex];
for (int i = 0; i < vertex; i++) {
list[i] = new LinkedList<>();
}
}
public void addEdge(int source, int destination) {
// add edge
list[source].addFirst(destination);
}
void DFS(int u, int v) {
boolean[] visited = new boolean[this.vertex];
START = u;
STOP = v;
explore(v, visited);
}
private void explore(int v, boolean[] visited) {
// TODO Auto-generated method stub
visited[v] = true;
visited[START] = false;
visited[STOP] = false;
Iterator<Integer> i = list[v].listIterator();
while (i.hasNext()) {
int n = i.next();
length++;
if (n == STOP) {
MAX = Math.max(MAX, length);
length = 0;
}
if (!visited[n])
explore(n, visited);
}
}
public static void main(String args[]) {
DAG2 g = new DAG2(8);
g.addEdge(1, 2);
g.addEdge(1, 3);
g.addEdge(2, 4);
g.addEdge(2, 5);
g.addEdge(3, 6);
g.addEdge(4, 7);
g.addEdge(5, 7);
g.addEdge(6, 5);
g.addEdge(6, 7);
// new
g.addEdge(2, 3);
g.addEdge(3, 5);
g.addEdge(5, 4);
}
}
The first thing I notice about the "visited" array is that if you're looking for more than one path, you might visit a node more than once (because more than one math might lead to it, e.g. 1 -> 3 -> 4 and 1 -> 2 -> 3 -> 4 will both visit 3).
My first instinct for a depth first search is to use a recursive search. I put together one like that looks like this:
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class DAG {
private Map<Integer, List<Integer>> graph = new HashMap<>();
public void addEdge(final int src, final int dst) {
if (!graph.containsKey(src)) {
graph.put(src, new LinkedList<Integer>());
}
graph.get(src).add(dst);
}
public List<Integer> findMaxPath(final int start, final int end) {
if (start == end) {
// The path is just this element, so return a list with just the
// start (or end).
final List<Integer> path = new LinkedList<>();
path.add(start);
return path;
}
if (!graph.containsKey(start)) {
// There is no path forward.
return null;
}
List<Integer> longestPath = null;
for (Integer next : graph.get(start)) {
final List<Integer> newPath = findMaxPath(next, end);
if (null != newPath) {
// Found a new path
if ( (null == longestPath)
|| (newPath.size() > longestPath.size()) )
{
// It was longer than the previous longest,
// it is new longest.
longestPath = newPath;
}
}
}
if (null != longestPath) {
// A path was found, include this node as the start of the path.
longestPath.add(0, start);
}
return longestPath;
}
public static void main(final String[] args) {
final DAG g = new DAG();
g.addEdge(1, 2);
g.addEdge(1, 3);
g.addEdge(1, 6);
g.addEdge(2, 4);
g.addEdge(3, 5);
g.addEdge(6, 7);
g.addEdge(7, 4);
g.addEdge(2, 6);
printPath(g.findMaxPath(1, 5));
g.addEdge(4, 5); // Make a longer path.
printPath(g.findMaxPath(1, 5));
}
private static void printPath(final List<Integer> path) {
System.out.println("Path:");
if (null != path) {
for (Integer p : path) {
System.out.println(" " + p);
}
} else {
System.out.println(" null");
}
}
}
To convert it into a non-recursive method, you can use a List as a Stack. Where findMaxPath() calls itself, instead you would push() the current node on the stack and use the next one, when that's done pop() the node and continue. Put all that in a loop, and it should work.

Insertion Sort for Singly Linked List [EXTERNAL]

I'm not sure where to start, but this is messy. Basically I need to write an Insertion Sort method for singly linked list - which causes enough problems, because usually for Insertion Sort - you're supposed to go through array/list elements backwards - which implementing into a singly linked list seems pointless, because the point of it - is that you're only capable of going forwards in the list and in addition to that -> I need to execute "swap" operations externally, which I do not completely understand how to perform that while using list structure.
This is my ArrayClass and Swap method that I used:
class MyFileArray : DataArray
{
public MyFileArray(string filename, int n, int seed)
{
double[] data = new double[n];
length = n;
Random rand = new Random(seed);
for (int i = 0; i < length; i++)
{
data[i] = rand.NextDouble();
}
if (File.Exists(filename)) File.Delete(filename);
try
{
using (BinaryWriter writer = new BinaryWriter(File.Open(filename,
FileMode.Create)))
{
for (int j = 0; j < length; j++)
writer.Write(data[j]);
}
}
catch (IOException ex)
{
Console.WriteLine(ex.ToString());
}
}
public FileStream fs { get; set; }
public override double this[int index]
{
get
{
Byte[] data = new Byte[8];
fs.Seek(8 * index, SeekOrigin.Begin);
fs.Read(data, 0, 8);
double result = BitConverter.ToDouble(data, 0);
return result;
}
}
public override void Swap(int j, double a)
{
Byte[] data = new Byte[16];
BitConverter.GetBytes(a).CopyTo(data, 0);
fs.Seek(8 * (j + 1), SeekOrigin.Begin);
fs.Write(data, 0, 8);
}
}
And this is my Insertion Sort for array:
public static void InsertionSort(DataArray items)
{
double key;
int j;
for (int i = 1; i < items.Length; i++)
{
key = items[i];
j = i - 1;
while (j >= 0 && items[j] > key)
{
items.Swap(j, items[j]);
j = j - 1;
}
items.Swap(j, key);
}
}
Now I somehow have to do the same exact thing - however using Singly Linked List, I'm given this kind of class to work with (allowed to make changes):
class MyFileList : DataList
{
int prevNode;
int currentNode;
int nextNode;
public MyFileList(string filename, int n, int seed)
{
length = n;
Random rand = new Random(seed);
if (File.Exists(filename)) File.Delete(filename);
try
{
using (BinaryWriter writer = new BinaryWriter(File.Open(filename,
FileMode.Create)))
{
writer.Write(4);
for (int j = 0; j < length; j++)
{
writer.Write(rand.NextDouble());
writer.Write((j + 1) * 12 + 4);
}
}
}
catch (IOException ex)
{
Console.WriteLine(ex.ToString());
}
}
public FileStream fs { get; set; }
public override double Head()
{
Byte[] data = new Byte[12];
fs.Seek(0, SeekOrigin.Begin);
fs.Read(data, 0, 4);
currentNode = BitConverter.ToInt32(data, 0);
prevNode = -1;
fs.Seek(currentNode, SeekOrigin.Begin);
fs.Read(data, 0, 12);
double result = BitConverter.ToDouble(data, 0);
nextNode = BitConverter.ToInt32(data, 8);
return result;
}
public override double Next()
{
Byte[] data = new Byte[12];
fs.Seek(nextNode, SeekOrigin.Begin);
fs.Read(data, 0, 12);
prevNode = currentNode;
currentNode = nextNode;
double result = BitConverter.ToDouble(data, 0);
nextNode = BitConverter.ToInt32(data, 8);
return result;
}
To be completely honest - I'm not sure neither how I'm supposed to implement Insertion Sort nor How then translate it into an external sort. I've used this code for not external sorting previously:
public override void InsertionSort()
{
sorted = null;
MyLinkedListNode current = headNode;
while (current != null)
{
MyLinkedListNode next = current.nextNode;
sortedInsert(current);
current = next;
}
headNode = sorted;
}
void sortedInsert(MyLinkedListNode newnode)
{
if (sorted == null || sorted.data >= newnode.data)
{
newnode.nextNode = sorted;
sorted = newnode;
}
else
{
MyLinkedListNode current = sorted;
while (current.nextNode != null && current.nextNode.data < newnode.data)
{
current = current.nextNode;
}
newnode.nextNode = current.nextNode;
current.nextNode = newnode;
}
}
So if someone could maybe give some kind of tips/explanations - or maybe if you have ever tried this - code examples how to solve this kind of problem, would be appreciated!
I actually have solved this fairly recently.
Here's the code sample that you can play around with, it should work out of the box.
public class SortLinkedList {
public static class LinkListNode {
private Integer value;
LinkListNode nextNode;
public LinkListNode(Integer value, LinkListNode nextNode) {
this.value = value;
this.nextNode = nextNode;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
public LinkListNode getNextNode() {
return nextNode;
}
public void setNextNode(LinkListNode nextNode) {
this.nextNode = nextNode;
}
#Override
public String toString() {
return this.value.toString();
}
}
public static void main(String...args) {
LinkListNode f = new LinkListNode(12, null);
LinkListNode e = new LinkListNode(11, f);
LinkListNode c = new LinkListNode(13, e);
LinkListNode b = new LinkListNode(1, c);
LinkListNode a = new LinkListNode(5, b);
print(sort(a));
}
public static void print(LinkListNode aList) {
LinkListNode iterator = aList;
while (iterator != null) {
System.out.println(iterator.getValue());
iterator = iterator.getNextNode();
}
}
public static LinkListNode sort(LinkListNode aList){
LinkListNode head = new LinkListNode(null, aList);
LinkListNode fringePtr = aList.getNextNode();
LinkListNode ptrBeforeFringe = aList;
LinkListNode findPtr;
LinkListNode prev;
while(fringePtr != null) {
Integer valueToInsert = fringePtr.getValue();
findPtr = head.getNextNode();
prev = head;
while(findPtr != fringePtr) {
System.out.println("fringe=" + fringePtr);
System.out.println(findPtr);
if (valueToInsert <= findPtr.getValue()) {
LinkListNode tmpNode = fringePtr.getNextNode();
fringePtr.setNextNode(findPtr);
prev.setNextNode(fringePtr);
ptrBeforeFringe.setNextNode(tmpNode);
fringePtr = ptrBeforeFringe;
break;
}
findPtr = findPtr.getNextNode();
prev = prev.getNextNode();
}
fringePtr = fringePtr.getNextNode();
if (ptrBeforeFringe.getNextNode() != fringePtr) {
ptrBeforeFringe = ptrBeforeFringe.getNextNode();
}
}
return head.getNextNode();
}
}
From a high level, what you are doing is you are keeping track of a fringe ptr, and you are inserting a node s.t. the it is in the correct spot in the corresponding sublist.
For instance, suppose I have this LL.
3->2->5->4
The first iteration, I have fringePtr at 2, and I want to insert 2 somewhere in the sublist that's before the fringe ptr, so I basically traverse starting from head going to the fringe ptr until the value is less than the current value. I also have a previous keeping track of the previous ptr (to account for null, I have a sentinel node at the start of my traversal so I can insert it at the head).
Then, when I see that it's less than the current, I know I need to insert it next to the previous, so I have to:
use a temporary ptr to keep track of my previous's current next.
bind previuos's next to my toInsert node.
bind my toInsert node's next to my temp node.
Then, to continue, you just advance your fringe ptr and try again, basically building up a sublist that is sorted as you move along until fringe hits the end.
i.e. the iterations will look like
1. 3->2->5->4
^
2. 2->3->5->4
^
3. 2->3->5->4
^
4. 2->3->4->5 FIN.

Nodes at a distance k in binary tree

You are given a function printKDistanceNodes which takes in a root node of a binary tree, a start node and an integer K. Complete the function to print the value of all the nodes (one-per-line) which are a K distance from the given start node in sorted order. Distance can be upwards or downwards.
private void printNodeAtN(Node root, Node start, int k) {
if (root != null) {
// calculate if the start is in left or right subtree - if start is
// root this variable is null
Boolean left = isLeft(root, start);
int depth = depth(root, start, 0);
if (depth == -1)
return;
printNodeDown(root, k);
if (root == start)
return;
if (left) {
if (depth > k) {
// print the nodes at depth-k level in left tree
printNode(depth - k - 1, root.left);
} else if (depth < k) {
// print the nodes at right tree level k-depth
printNode(k - depth - 1, root.right);
} else {
System.out.println(root.data);
}
} else {
// similar if the start is in right subtree
if (depth > k) {
// print the nodes at depth-k level in left tree
printNode(depth - k - 1, root.right);
} else if (depth < k) {
// print the nodes at right tree level k-depth
printNode(k - depth - 1, root.left);
} else {
System.out.println(root.data);
}
}
}
}
// print the nodes at depth - "level" from root
void printNode(int level, Node root) {
if (level == 0 && root != null) {
System.out.println(root.data);
} else {
printNode(level - 1, root.left);
printNode(level - 1, root.right);
}
}
// print the children of the start
void printNodeDown(Node start, int k) {
if (start != null) {
if (k == 0) {
System.out.println(start.data);
}
printNodeDown(start.left, k - 1);
printNodeDown(start.right, k - 1);
}
}
private int depth(Node root, Node node, int d) {
if (root == null)
return -1;
if (root != null && node == root) {
return d;
} else {
int left = depth(root.left, node, d + 1);
int right = depth(root.right, node, d + 1);
if (left > right)
return left;
else
return right;
}
}
There is at most one node at distance K which upwards - just start from the start node and move up along parents for K steps. Add this to a sorted data structure.
Then you need to add the downward nodes. To do that you can do a BFS with queue, where you store the depth together with the node when you insert it in the queue (the starting node is at level 0, it's children at level 1 and so on). Then when you pop the nodes if they are at level K add them to the sorted data structure. when you start poping nodes at level K+1 you can stop.
Finally print the nodes from the sorted data structure (they will be sorted).
EDIT: If there is no parent pointer:
Write a recursive function int Go(Node node), which returns the depth of the start node with respect to the passed in node and -1 if the subtree of node doesn't contain start. The function will find the K-th parent as a side effect. Pseudo code:
static Node KthParent = null;
static Node start = ...;
static int K = ...;
int Go(Node node) {
if (node == start) return 0;
intDepth = -1;
if(node.LeftChild != null) {
int leftDepth = Go(node.LeftChild);
if(leftDepth >= 0) intDepth = leftDepth+1;
}
if (intDepth < 0 && node.rightChild != null) {
int rightDepth = Go(node.RightChild);
if(rightDepth >= 0) intDepth = rightDepth+1;
}
if(intDepth == K) KthParent = node;
return intDepth;
}
private static int printNodeAtK(Node root, Node start, int k, boolean found){
if(root != null){
if(k == 0 && found){
System.out.println(root.data);
}
if(root==start || found == true){
int leftd = printNodeAtK(root.left, start, k-1, true);
int rightd = printNodeAtK(root.right,start,k-1,true);
return 1;
}else{
int leftd = printNodeAtK(root.left, start, k, false);
int rightd = printNodeAtK(root.right,start,k,false);
if(leftd == k || rightd == k){
System.out.println(root.data);
}
if(leftd != -1 && leftd > rightd){
return leftd+1;
}else if(rightd != -1 && rightd>leftd){
return rightd+1;
}else{
return -1;
}
}
}
return -1;
}
struct node{
int data;
node* left;
node* right;
bool printed;
};
void print_k_dist(node** root,node** p,int k,int kmax);
void reinit_printed(node **root);
void print_k_dist(node** root,node **p,int k,int kmax)
{
if(*p==NULL) return;
node* par=parent(root,p);
if(k<=kmax &&(*p)->printed==0)
{
cout<<(*p)->data<<" ";
(*p)->printed=1;
k++;
print_k_dist(root,&par,k,kmax);
print_k_dist(root,&(*p)->left,k,kmax);
print_k_dist(root,&(*p)->right,k,kmax);
}
else
return;
}
void reinit_printed(node **root)
{
if(*root==NULL) return;
else
{
(*root)->printed=0;
reinit_printed(&(*root)->left);
reinit_printed(&(*root)->right);
}
}
typedef struct node
{
int data;
struct node *left;
struct node *right;
}node;
void printkdistanceNodeDown(node *n, int k)
{
if(!n)
return ;
if(k==0)
{
printf("%d\n",n->data);
return;
}
printkdistanceNodeDown(n->left,k-1);
printkdistanceNodeDown(n->right,k-1);
}
void printkdistanceNodeDown_fromUp(node* target ,int *k)
{
if(!target)
return ;
if(*k==0)
{
printf("%d\n",target->data);
return;
}
else
{
int val=*k;
printkdistanceNodeDown(target,val-1);
}
}
int printkdistanceNodeUp(node* root, node* n , int k)
{
if(!root)
return 0;
if(root->data==n->data)
return 1;
int pl=printkdistanceNodeUp(root->left,n,k);
int pr=printkdistanceNodeUp(root->right,n,k);
if(pl )
{
k--;
if(k==0)
printf("%d\n",root->data);
else
{
printkdistanceNodeDown_fromUp(root->right,k);
printkdistanceNodeDown_fromUp(root->left,k-1);
}
return 1;
}
if(pr )
{
k--;
if(k==0)
printf("%d\n",root->data);
else
{
printkdistanceNodeDown_fromUp(root->left,k);
printkdistanceNodeDown_fromUp(root->right,k-1);
}
return 1;
}
return 0;
}
void printkdistanceNode(node* root, node* n , int k )
{
if(!root)
return ;
int val=k;
printkdistanceNodeUp(root,n,k);
printkdistanceNodeDown(n,val);
}
caller function: printkdistanceNode(root,n,k);
The output will print all the nodes at a distance k from given node upward and downward.
Here in this code PrintNodesAtKDistance will first try to find the required node.
if(root.value == requiredNode)
When we find the desired node we print all the child nodes at the distance K from this node.
Now our task is to print all nodes which are in other branches(Go up and print). We return -1 till we didn't find our desired node. As we get our desired node we get lPath or rPath >=0 . Now we have to print all nodes which are at distance (lPath/rPath) -1
public void PrintNodes(Node Root, int requiredNode, int iDistance)
{
PrintNodesAtKDistance(Root, requiredNode, iDistance);
}
public int PrintNodesAtKDistance(Node root, int requiredNode, int iDistance)
{
if ((root == null) || (iDistance < 0))
return -1;
int lPath = -1, rPath = -1;
if(root.value == requiredNode)
{
PrintChildNodes(root, iDistance);
return iDistance - 1;
}
lPath = PrintNodesAtKDistance(root.left, requiredNode, iDistance);
rPath = PrintNodesAtKDistance(root.right, requiredNode, iDistance);
if (lPath > 0)
{
PrintChildNodes(root.right, lPath - 1);
return lPath - 1;
}
else if(lPath == 0)
{
Debug.WriteLine(root.value);
}
if(rPath > 0)
{
PrintChildNodes(root.left, rPath - 1);
return rPath - 1;
}
else if (rPath == 0)
{
Debug.WriteLine(root.value);
}
return -1;
}
public void PrintChildNodes(Node aNode, int iDistance)
{
if (aNode == null)
return;
if(iDistance == 0)
{
Debug.WriteLine(aNode.value);
}
PrintChildNodes(aNode.left, iDistance - 1);
PrintChildNodes(aNode.right, iDistance - 1);
}
Here is complete java program . Inspired from geeksforgeeks Algorith
// Java program to print all nodes at a distance k from given node
class BinaryTreePrintKDistance {
Node root;
/*
* Recursive function to print all the nodes at distance k in tree (or
* subtree) rooted with given root.
*/
void printKDistanceForDescendant(Node targetNode, int currentDist,
int inputDist) {
// Base Case
if (targetNode == null || currentDist > inputDist)
return;
// If we reach a k distant node, print it
if (currentDist == inputDist) {
System.out.print(targetNode.data);
System.out.println("");
return;
}
++currentDist;
// Recur for left and right subtrees
printKDistanceForDescendant(targetNode.left, currentDist, inputDist);
printKDistanceForDescendant(targetNode.right, currentDist, inputDist);
}
public int printkdistance(Node targetNode, Node currentNode,
int inputDist) {
if (currentNode == null) {
return -1;
}
if (targetNode.data == currentNode.data) {
printKDistanceForDescendant(currentNode, 0, inputDist);
return 0;
}
int ld = printkdistance(targetNode, currentNode.left, inputDist);
if (ld != -1) {
if (ld + 1 == inputDist) {
System.out.println(currentNode.data);
} else {
printKDistanceForDescendant(currentNode.right, 0, inputDist
- ld - 2);
}
return ld + 1;
}
int rd = printkdistance(targetNode, currentNode.right, inputDist);
if (rd != -1) {
if (rd + 1 == inputDist) {
System.out.println(currentNode.data);
} else {
printKDistanceForDescendant(currentNode.left, 0, inputDist - rd
- 2);
}
return rd + 1;
}
return -1;
}
// Driver program to test the above functions
#SuppressWarnings("unchecked")
public static void main(String args[]) {
BinaryTreePrintKDistance tree = new BinaryTreePrintKDistance();
/* Let us construct the tree shown in above diagram */
tree.root = new Node(20);
tree.root.left = new Node(8);
tree.root.right = new Node(22);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(12);
tree.root.left.right.left = new Node(10);
tree.root.left.right.right = new Node(14);
Node target = tree.root.left;
tree.printkdistance(target, tree.root, 2);
}
static class Node<T> {
public Node left;
public Node right;
public T data;
Node(T data) {
this.data = data;
}
}
}

Resources