# Overview

It seems that coding tests are conducted overseas in interviews with engineers, and in many cases, the main thing is to implement specific functions and classes according to the theme.

Apparently, many engineers take measures on the site called LetCode.

It is a site that trains the algorithmic power that can withstand the coding test that is being done in the early story, and it is an inevitable path for those who want to build a career at an overseas tech company.

I wrote it in a big way, but I have no plans to have such an interview at the moment.

However, as an IT engineer, it would be better to have the same level of algorithm power as a person, so I would like to solve the problem irregularly and write down the method I thought at that time as a memo.

Leetcode

I'm solving it with Python3.

** Technical Blog Started! !! ** ** I think the technology will write about LetCode, Django, Nuxt, and so on. ** This is faster to update **, so please bookmark it!

# problem

102. Binary Tree Level Order Traversal The difficulty level is Medium. It is an excerpt from the problem collection as before.

The problem is, given a binary tree, design an algorithm that returns a list of equivalents next to the value hierarchy of that node. (That is, 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]
]
``````

An example is like this. I hope you understand what I mean.

# solution

Solved by DFS.

``````# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
ans,level = [],0
self.dfs(root,level,ans)
return ans

def dfs(self,root,level,ans):
if not root:
return
if len(ans) < level+1:
ans.append([])
ans[level].append(root.val)
self.dfs(root.left,level+1,ans)
self.dfs(root.right,level+1,ans)
# Runtime: 32 ms, faster than 86.02% of Python3 online submissions for Binary Tree Level Order Traversal.
# Memory Usage: 14.2 MB, less than 43.09% of Python3 online submissions for Binary Tree Level Order Traversal.
``````

It's a simple DFS. Since it is decided to return it as a list, if you increase the length of the list, you can cover the elements of the hierarchy well.

This time I solved it with a depth-first search that I am accustomed to, but there are examples of solving with BFS and answers using cues in discuss, so it seems that an individual's favorite solution will appear. That's a problem.

So that's it for this time. Thank you for your hard work.