Created
January 23, 2016 11:12
-
-
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},
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
/** | |
* 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