Last active
August 9, 2017 03:16
-
-
Save cixuuz/89b3075f851480dcceb8f15a83e5409f to your computer and use it in GitHub Desktop.
[102. Binary Tree Level Order Traversal] #leetcode #lc0102
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
public class Solution { | |
public List<List<Integer>> levelOrder(TreeNode root) { | |
List<List<Integer>> res = new LinkedList<List<Integer>>(); | |
Queue<TreeNode> q = new LinkedList<TreeNode>(); | |
if (root == null) return res; | |
q.offer(root); | |
while (!q.isEmpty()) { | |
Integer levelLength = q.size(); | |
List<Integer> list = new LinkedList<Integer>(); | |
for (int i = 0; i < levelLength; i++) { | |
TreeNode node = q.poll(); | |
list.add(node.val); | |
if (node.left != null) q.offer(node.left); | |
if (node.right != null) q.offer(node.right); | |
} | |
res.add(list); | |
} | |
return res; | |
} | |
} | |
// recursive | |
public class Solution1 { | |
List<List<Integer>> res = new ArrayList<List<Integer>>(); | |
public List<List<Integer>> levelOrder(TreeNode root) { | |
helper(root, 0); | |
return res; | |
} | |
private void helper(TreeNode root, Integer depth) { | |
if (root == null) return; | |
if (res.size() == depth) res.add(new LinkedList<Integer>()); | |
res.get(depth).add(root.val); | |
helper(root.left, depth+1); | |
helper(root.right, depth+1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment