Created
August 18, 2015 07:05
-
-
Save xynophon/9967dfbd7f8f63818a3a to your computer and use it in GitHub Desktop.
LeetCode Binary Tree Level Order Traversal
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
| 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