Skip to content

Instantly share code, notes, and snippets.

@kylelong
Created October 31, 2019 16:51
Show Gist options
  • Save kylelong/1d62cbcc1df84a28f3217995669e485b to your computer and use it in GitHub Desktop.
Save kylelong/1d62cbcc1df84a28f3217995669e485b to your computer and use it in GitHub Desktop.
Binary Tree Level Order Traversal
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class BTLOT {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> list = new ArrayList<>();
if(root == null) return list;
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
TreeNode curr = null;
ArrayList<Integer> currList = new ArrayList<Integer>();
currList.add(root.val);
list.add(currList);
while(!q.isEmpty()){
currList = new ArrayList<Integer>();
int size = q.size();
for(int i = 0; i < size; i++){
curr = q.poll();
if(curr.left != null){
q.add(curr.left);
currList.add(curr.left.val);
}
if(curr.right != null){
q.add(curr.right);
currList.add(curr.right.val);
}
}
if(currList.size() > 0){
list.add(currList);
}
}
return list;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment