Skip to content

Instantly share code, notes, and snippets.

@kendhia
Created January 23, 2016 11:12
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 kendhia/cd8516702f826ac8e55f to your computer and use it in GitHub Desktop.
Save kendhia/cd8516702f826ac8e55f to your computer and use it in GitHub Desktop.
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). For example: Given binary tree {3,9,20,#,#,15,7},
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List res = new ArrayList<>();
if (root == null) return res;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while(!queue.isEmpty()) {
ArrayList level = new ArrayList();
int size = queue.size();
//Since the items that exist in the queue right now
// all are of the same level, we can do the following
for (int i =0; i < size; i++) {
TreeNode curr = queue.poll();
level.add(curr.val);
if (curr.left != null) queue.offer(curr.left);
if (curr.right != null) queue.offer(curr.right);
}
res.add(level);
}
return res;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment