Skip to content

Instantly share code, notes, and snippets.

@chrislukkk
Created July 8, 2014 02:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chrislukkk/15bb4a11c3c4872d0e6a to your computer and use it in GitHub Desktop.
Save chrislukkk/15bb4a11c3c4872d0e6a to your computer and use it in GitHub Desktop.
CareerCup_4.4 - Create linked lists from binary tree
package Chapter4;
import java.util.LinkedList;
import java.util.Queue;
public class LevelOrderTraverse {
public static LinkedList<LinkedList<TreeNode<Integer>>> getLists(
BinaryTree<Integer> tree) {
LinkedList<LinkedList<TreeNode<Integer>>> result = new LinkedList<>();
TreeNode<Integer> root = tree.root();
if (root == null)
return result;
// initial root
Queue<TreeNode<Integer>> queue = new LinkedList<TreeNode<Integer>>();
queue.add(root);
int nextLevelSize = 0;
int size = 1;
while (!queue.isEmpty()) {
LinkedList<TreeNode<Integer>> levellist = new LinkedList<>();
while (size > 0) {
//one level
TreeNode<Integer> node = queue.remove();
size--;
levellist.add(node);
if (node.left != null) {
queue.add(node.left);
nextLevelSize++;
}
if (node.right != null) {
queue.add(node.right);
nextLevelSize++;
}
}
//set to go to next level
result.add(levellist);
size = nextLevelSize;
nextLevelSize = 0;
}
return result;
}
public static void print(LinkedList<LinkedList<TreeNode<Integer>>> list) {
for(int i = 0; i < list.size(); i++) {
System.out.print("level " + i + " ---- ");
for (TreeNode<Integer> node : list.get(i)) {
System.out.print(node.key + "; ");
}
System.out.println();
}
}
public static void main(String[] args) {
/* _______7______
/ \
__10__ ___2
/ \ /
4 3 _8
\ /
1 11 */
Integer[] pre = { 7, 10, 4, 3, 1, 2, 8, 11 };
Integer[] in = { 4, 10, 3, 1, 7, 11, 8, 2 };
BinaryTree<Integer> t = BinaryTreeBuilder.buildTree(pre, in);
print(getLists(t));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment