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]
]
思路:题目是给一棵二叉树,返回层级遍历的节点值。本题可以使用dfs解题。在dfs函数中添加一个记录层数的变量即可。
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
dfs(root, res, 0);
return res;
}
private void dfs(TreeNode root, List<List<Integer>> res, int count) {
if(root == null)
return;
if(res.size() < count+1)
res.add(new ArrayList<Integer>());
res.get(count).add(root.val);
dfs(root.left, res, count+1);
dfs(root.right, res, count+1);
}