Skip to content

Instantly share code, notes, and snippets.

@jacygao
Last active November 6, 2020 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jacygao/e2c5ed4742dea1c92c8a68558908a0ef to your computer and use it in GitHub Desktop.
Save jacygao/e2c5ed4742dea1c92c8a68558908a0ef to your computer and use it in GitHub Desktop.
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level)
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> out = new ArrayList<List<Integer>>();
dfs(root, out, -1);
return out;
}
public void dfs(TreeNode node, List<List<Integer>> out, int dep) {
dep++;
if(node != null) {
visit(node, out, dep);
dfs(node.left, out, dep);
dfs(node.right, out, dep);
}
}
public void visit(TreeNode node, List<List<Integer>> out, int dep) {
if (out.size() <= dep){
out.add(new ArrayList<Integer>());
}
out.get(dep).add(node.val);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment