Given a binary tree, return thelevel ordertraversal 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]
]
Solution
Recursive solution.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
// each level is one index in result list (we pass level as parameter in the method, if it does not exist, we create it)
traverse(root, result, 0);
return result;
}
public void traverse(TreeNode node, List<List<Integer>> list, int level) {
if (node == null) return;
if (level == list.size()) {
list.add(new ArrayList<>());
}
list.get(level).add(node.val);
traverse(node.left, list, level + 1);
traverse(node.right, list, level + 1);
}
}
Non recursive solution.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> ans = new ArrayList<>();
Queue<TreeNode> q = new LinkedList<>();
if (root != null) {
q.offer(root);
}
TreeNode cur;
while (!q.isEmpty()) {
int size = q.size();
List<Integer> subAns = new LinkedList<Integer>();
for (int i = 0; i < size; ++i) { // traverse nodes in the same level
cur = q.poll();
subAns.add(cur.val); // visit the root
if (cur.left != null) {
q.offer(cur.left); // push left child to queue if it is not null
}
if (cur.right != null) {
q.offer(cur.right); // push right child to queue if it is not null
}
}
ans.add(subAns);
}
return ans;
}
}