Skip to content

Instantly share code, notes, and snippets.

Created September 26, 2019 17:19
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
public void dfsHelper(TreeNode node, int depth, Map<Integer, List<Integer>> depthToListMap) {
if (node == null) {
if (!depthToListMap.containsKey(depth)) {
depthToListMap.put(depth, new ArrayList<Integer>());
dfsHelper(node.left, depth + 1, depthToListMap);
dfsHelper(node.right, depth + 1, depthToListMap);
// this is a clever way to implement level order traversal using dfs with the help of a map to keep overwriting the
// depth info
public List<List<Integer>> levelOrderDfs(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) {
return res;
Map<Integer, List<Integer>> depthToListMap = new HashMap<>();
this.dfsHelper(root, 1, depthToListMap);
int i = 1;
while (depthToListMap.containsKey(i)) {
return res;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment