-
-
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).
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
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