leetcode每日一题 429.N 叉树的层序遍历
简单的DFS遍历
class Solution {
public List<List<Integer>> levelOrder(Node root) {
if(root == null){
return new ArrayList<>();
}
List<List<Integer>> result = new ArrayList<>();
dfs(result,root,0);
return result;
}
private void dfs(List<List<Integer>> result, Node root, int i) {
List<Integer> list;
if(result.size() <= i){
list = new ArrayList<>();
result.add(list);
}else{
list = result.get(i);
}
list.add(root.val);
if(root.children != null){
for (Node child : root.children) {
dfs(result,child,i+1);
}
}
}
}


浙公网安备 33010602011771号