Problem
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]
]
Solution (Java)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) {
return result;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
queue.add(null);
List<Integer> level = new ArrayList<>();
while (!queue.isEmpty()) {
root = queue.remove();
while (!queue.isEmpty() && root != null) {
level.add(root.val);
if (root.left != null) {
queue.add(root.left);
}
if (root.right != null) {
queue.add(root.right);
}
root = queue.remove();
}
result.add(level);
level = new ArrayList<>();
if (!queue.isEmpty()) {
queue.add(null);
}
}
return result;
}
}
Solution 1
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrder = function(root) {
if (!root) return [];
return helper([[root]], 0);
};
var helper = function (res, level) {
var now = res[level];
var next = [];
for (var i = 0; i < now.length; i++) {
if (now[i].left) next.push(now[i].left);
if (now[i].right) next.push(now[i].right);
now[i] = now[i].val;
}
if (next.length) {
res.push(next);
helper(res, level + 1);
}
return res;
};
Explain:
bfs
Complexity:
- Time complexity : O(n).
- Space complexity : O(n).
Solution 2
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrder = function(root) {
return helper([], root, 0);
};
var helper = function (res, root, level) {
if (root) {
if (!res[level]) res[level] = [];
res[level].push(root.val);
helper(res, root.left, level + 1);
helper(res, root.right, level + 1);
}
return res;
};
Explain:
dfs
Complexity:
- Time complexity : O(n).
- Space complexity : O(n).