# 102.Binary-Tree-Level-Order-Traversal

## ้ข็ฎๅฐๅ

http://www.lintcode.com/problem/binary-tree-level-order-traversal/

http://www.jiuzhang.com/solutions/binary-tree-level-order-traversal/

https://leetcode.com/problems/binary-tree-level-order-traversal/

## ้ข็ฎๆ่ฟฐ

``````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,null,null,15,7],
3
/ \
9  20
/  \
15   7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]``````

## ไปฃ็ 

### Approach 1: BFS

``````public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();

if (root == null) return result;

queue.offer(root);

while (!queue.isEmpty()) {
ArrayList<Integer> level = new ArrayList<Integer>();
int size = queue.size();
for (int i = 0; i < size; i++) {
}
}
}
}

return result;
}
}``````

### Approach 2: DFS

``````class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> results = new ArrayList<List<Integer>>();
if (root == null)    return results;

int maxLevel = 0;
while (true) {
List<Integer> level = new ArrayList<Integer>();
dfs(root, level, 0, maxLevel);
if (level.size() == 0) {
break;
}

maxLevel++;
}

return results;
}

private void dfs(TreeNode root, List<Integer> level, int curtLevel, int maxLevel) {
if (root == null || curtLevel > maxLevel) return;

if (curtLevel == maxLevel) {
return;
}

dfs(root.left, level, curtLevel + 1, maxLevel);
dfs(root.right, level, curtLevel + 1, maxLevel);
}
}``````

### Approach 3; BFS, two queues

``````class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (root == null) return result;

List<TreeNode> Q1 = new ArrayList<TreeNode>();
List<TreeNode> Q2 = new ArrayList<TreeNode>();

while (Q1.size() != 0) {
List<Integer> level = new ArrayList<Integer>();
Q2.clear();
for (int i = 0; i < Q1.size(); i++) {
TreeNode node = Q1.get(i);
if (node.left != null) {
}
if (node.right != null) {
}
}

List<TreeNode> temp = Q1;
Q1 = Q2;
Q2 = temp;