Created
March 1, 2015 17:00
-
-
Save zachschultz/80b6ad6d818e1329c381 to your computer and use it in GitHub Desktop.
Create a Linked List for each depth of a Binary Search 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
import java.util.*; | |
public class LinkedListForEachDepth { | |
public static void main(String[] args) { | |
Node root = new Node(12); | |
// ... create BST with nodes | |
// create our list of LinkedLists | |
ArrayList<LinkedList<Node>> lists = makeLinkedLists(root); | |
// print them | |
int count = 0; | |
for (LinkedList<Node> ll : lists) { | |
Iterator<Node> iter = ll.iterator(); | |
System.out.println("Linked list " + count++); | |
while (iter.hasNext()) { | |
System.out.print(iter.next() + " "); | |
} | |
System.out.println(); | |
} | |
} | |
public static ArrayList<LinkedList<Node>> makeLinkedLists(Node root) { | |
LinkedList<Node> current = new LinkedList<Node>(); | |
LinkedList<Node> nextLevel = new LinkedList<Node>(); | |
ArrayList<LinkedList<Node>> lists = new ArrayList<LinkedList<Node>>(); | |
current.add(root); | |
while (!current.isEmpty()) { | |
LinkedList<Node> newLL = (LinkedList<Node>)current.clone(); | |
lists.add(newLL); | |
while (!current.isEmpty()) { | |
Node n = current.remove(); | |
if (n.left != null) nextLevel.add(n.left); | |
if (n.right != null) nextLevel.add(n.right); | |
} | |
if (current.isEmpty()) { | |
current = nextLevel; | |
nextLevel = new LinkedList<Node>(); | |
} | |
} | |
return lists; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment