Skip to content

Instantly share code, notes, and snippets.

@orhanobut
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save orhanobut/9362671 to your computer and use it in GitHub Desktop.
Save orhanobut/9362671 to your computer and use it in GitHub Desktop.
find the node in k distance in a given tree list, solution 1 : shifting -> complexity = o (n)
public class HelloWorld {
public static void main(String[] args) {
Node r = new Node(0);
r.left = new Node(1);
r.right = new Node(2);
r.left.left = new Node(3);
r.left.right = new Node(4);
r.left.left.left = new Node(5);
r.right.right = new Node(6);
r.right.left = new Node(7);
r.right.left.right = new Node(8);
find(r, 2, null, -1);
}
public static class Node {
Node parent;
Node left;
Node right;
int value;
public Node(int value) {
this.value = value;
}
}
public static void find(Node n, int k, int[] list, int last) {
if (list == null) {
list = new int[k];
for (int i = 0; i < k; i++) {
list[i] = -1;
}
}
if (n.left == null && n.right == null) {
System.out.println("\nleaf : " + n.value);
if (list[k - 1] != -1) {
int i = last + 1 == k ? 0 : last + 1;
System.out.println("node in k distance : " + list[i]);
}
}
if (n.left != null) {
n.left.parent = n;
int[] temp = new int[k];
temp = list.clone();
int templast = getLastIndex(temp, last, k, n.value);
find(n.left, k, temp, templast);
}
if (n.right != null) {
n.right.parent = n;
int[] temp = new int[k];
temp = list.clone();
int templast = getLastIndex(temp, last, k, n.value);
find(n.right, k, temp, templast);
}
}
private static int getLastIndex(int[] temp, int last, int k, int value) {
int templast = last;
if (templast + 1 < k) {
temp[templast + 1] = value;
templast++;
} else {
temp[templast + 1 - k] = value;
templast = templast + 1 - k;
}
return templast;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment