Skip to content

Instantly share code, notes, and snippets.

@jason51122
Created July 27, 2014 04:01
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 jason51122/f22ed431db4a7dd8fbf3 to your computer and use it in GitHub Desktop.
Save jason51122/f22ed431db4a7dd8fbf3 to your computer and use it in GitHub Desktop.
4.4 Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth (e.g., if you have a tree with depth D,you'll have D linked lists).
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
left = null;
right = null;
}
}
public ArrayList<LinkedList<TreeNode>> treeDepth2LinkedList(TreeNode root) {
if (root == null) {
return null;
}
ArrayList<LinkedList<TreeNode>> result = new ArrayList<LinkedList<TreeNode>>();
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while (!queue.isEmpty()) {
int count = queue.size();
LinkedList<TreeNode> depth = new LinkedList<TreeNode>();
while (count > 0) {
TreeNode cur = queue.remove();
depth.add(cur);
if (cur.left != null) {
queue.add(cur.left);
}
if (cur.right != null) {
queue.add(cur.right);
}
count--;
}
result.add(depth);
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment