Last active
August 29, 2015 14:14
-
-
Save ssinganamalla/6cfcc4b4af64041f4924 to your computer and use it in GitHub Desktop.
Given a BST and a node (say target), find K nearest neighbors. http://www.geeksforgeeks.org/print-nodes-distance-k-given-node-binary-tree/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.mycompany.tree; | |
import java.util.*; | |
import java.util.List; | |
public class BinarySearchTree { | |
private Node root; | |
public List<Node> printKNeighbours(int value, int k) { | |
List<Node> path = pathToRoot(value); | |
if (path.size() == 0){ | |
return Collections.EMPTY_LIST; | |
} | |
for (int i = 0; i < path.size(); i++) { | |
Node current = path.get(i); | |
current.level = i; | |
} | |
return fetchkNeighbours(k); | |
} | |
private List<Node> fetchkNeighbours(int k) { | |
List<Node> kList = new ArrayList<Node>(); | |
LinkedList<Node> list = new LinkedList<Node>(); | |
list.add(root); | |
if (root.level == k) { | |
kList.add(root); | |
} | |
while (!list.isEmpty()) { | |
Node node = list.poll(); | |
if (node.left != null) { | |
node.left.level = node.level + 1; | |
list.addFirst(node.left); | |
if (node.left.level == k){ | |
kList.add(node.left); | |
} | |
} | |
if (node.right != null) { | |
node.right.level = node.level + 1; | |
list.addFirst(node.right); | |
if (node.right.level == k){ | |
kList.add(node.right); | |
} | |
} | |
} | |
return kList; | |
} | |
private List<Node> pathToRoot(int value) { | |
List<Node> normal = findPath(value); | |
Collections.reverse(normal); | |
return normal; | |
} | |
/* | |
Returns a path to the node containing value. Otherwise returns empty list | |
*/ | |
private List<Node> findPath(int value) { | |
if (root == null) { | |
return Collections.EMPTY_LIST; | |
} | |
List<Node> path = new ArrayList<Node>(); | |
Node current = root; | |
while (current != null) { | |
path.add(current); | |
if (current.value == value) { | |
break; | |
} | |
if (value < current.value) { | |
current = current.left; | |
}else { | |
current = current.right; | |
} | |
} | |
return current != null ? path : Collections.EMPTY_LIST; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.mycompany.tree; | |
public class Node { | |
public int value; | |
public Node left; | |
public Node right; | |
public int level; | |
public Node(int value) { | |
this.value = value; | |
this.level = -1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment