Last active
November 6, 2020 12:39
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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