Created
April 12, 2017 23:26
-
-
Save artlovan/c9e176a0acbedb30968eb07229877e61 to your computer and use it in GitHub Desktop.
Search by Depth & by Breadth
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
import java.util.*; | |
import java.util.stream.Stream; | |
import static java.util.stream.Collectors.toList; | |
public class SearchBreadthDepth { | |
/** | |
node5 | |
node3 node4 | |
node2 | |
node1 | |
node5, node3, node4, node2, node1 | |
node5, node3, node2, node1, node4 | |
*/ | |
public static void main(String[] args) { | |
Node n1_left = new Node("node1", null, null); | |
Node n2_right = new Node("node2", n1_left, null); | |
Node n3_left = new Node("node3", null, n2_right); | |
Node n4_right = new Node("node4", null, null); | |
Node n5 = new Node("node5", n3_left, n4_right); | |
List<Node> nodes = Search.byBreadth(n5); | |
System.out.println(nodes); | |
List<Node> nodes2 = Search.byDepth(n5); | |
System.out.println(nodes2); | |
} | |
} | |
class Node { | |
private String nodeName; | |
private Node leftNode; | |
private Node rightNode; | |
public Node(String nodeName, Node leftNode, Node rightNode) { | |
this.nodeName = nodeName; | |
this.leftNode = leftNode; | |
this.rightNode = rightNode; | |
} | |
public List<Node> getSubNodes() { | |
return Stream.of(leftNode, rightNode) | |
.filter(Objects::nonNull) | |
.collect(toList()); | |
} | |
@Override | |
public String toString() { | |
return this.nodeName; | |
} | |
} | |
class Search { | |
public static List<Node> byBreadth(Node node) { | |
List<Node> unvisited = new ArrayList<Node>(){{add(node);}}; | |
List<Node> visited = new ArrayList<>(); | |
visited.add(node); | |
while (!unvisited.isEmpty()) { | |
List<Node> nodes = unvisited | |
.stream() | |
.map(Node::getSubNodes) | |
.flatMap(Collection::stream) | |
.filter(n -> !visited.contains(n)) | |
.collect(toList()); | |
visited.addAll(nodes); | |
unvisited = nodes; | |
} | |
return visited; | |
} | |
public static List<Node> byDepth(Node node) { | |
List<Node> unvisited = new ArrayList<Node>(){{add(node);}}; | |
List<Node> visited = new ArrayList<>(); | |
while (!unvisited.isEmpty()) { | |
Node currentNode = unvisited.remove(0); | |
List<Node> collect = currentNode.getSubNodes() | |
.stream() | |
.filter(n -> !visited.contains(n)) | |
.collect(toList()); | |
visited.add(currentNode); | |
unvisited.addAll(0, collect); | |
} | |
return visited; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment