Created
August 24, 2013 01:49
-
-
Save charlespunk/6325564 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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}, | |
3 | |
/ \ | |
9 20 | |
/ \ | |
15 7 | |
return its level order traversal as: | |
[ | |
[3], | |
[9,20], | |
[15,7] | |
] |
This file contains hidden or 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 binary tree | |
* public class TreeNode { | |
* int val; | |
* TreeNode left; | |
* TreeNode right; | |
* TreeNode(int x) { val = x; } | |
* } | |
*/ | |
public class Solution { | |
public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) { | |
// Start typing your Java solution below | |
// DO NOT write main() function | |
ArrayList<ArrayList<Integer>> all = new ArrayList<ArrayList<Integer>>(); | |
if(root == null) return all; | |
Queue<TreeNode> q = new LinkedList<TreeNode>(); | |
q.offer(root); | |
while(!q.isEmpty()){ | |
ArrayList<Integer> one = new ArrayList<Integer>(); | |
for(TreeNode node: q) one.add(node.val); | |
all.add(one); | |
Queue<TreeNode> qNext = new LinkedList<TreeNode>(); | |
while(!q.isEmpty()){ | |
TreeNode node = q.poll(); | |
if(node.left != null) qNext.offer(node.left); | |
if(node.right != null) qNext.offer(node.right); | |
} | |
q = qNext; | |
} | |
return all; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment