Skip to content

Instantly share code, notes, and snippets.

@xynophon
Created August 18, 2015 07:05
Show Gist options
  • Select an option

  • Save xynophon/9967dfbd7f8f63818a3a to your computer and use it in GitHub Desktop.

Select an option

Save xynophon/9967dfbd7f8f63818a3a to your computer and use it in GitHub Desktop.
LeetCode Binary Tree Level Order Traversal
import java.util.*;
public class BinaryTreeLevelOrderTraversal {
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> ret = new ArrayList<>();
if(root == null) return ret;
Queue<TreeNode> qu = new LinkedList<>();
qu.add(root);
while(!qu.isEmpty()){
int items = qu.size();
List<Integer> list = new ArrayList<>();
for (int i = 0; i < items; i++) {
if(qu.peek().left != null)qu.add(qu.peek().left);
if(qu.peek().right != null)qu.add(qu.peek().right);
list.add(qu.remove().val);
}
ret.add(list);
}
return ret;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment