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.
As a countermeasure, it seems that a site called Let Code will take measures.
A site that trains algorithmic power that can withstand coding tests that are often done in the home.
I think it's better to have the algorithm power of a human being, so I'll solve the problem irregularly and write down the method I thought at that time as a memo.
Leet Code Table of Contents Starting from Zero
Last time Leet Code Day 22 starting from zero "141. Linked List Cycle"
Basically, I would like to solve the easy acceptance in descending order.
Twitter I'm doing it.
226. Invert Binary Tree The difficulty level is easy. Excerpt from Top 100 Liked Questions. There are only 10 easy questions left in the Top 100 Liked Questions, so I would like to study more and be able to solve the Medium level quickly.
The problem is that the structure of a given binary tree is completely inverted.
Example:
Input:
4
/ \
2 7
/ \ / \
1 3 6 9
Output:
4
/ \
7 2
/ \ / \
9 6 3 1
There is no particular explanation because you can see it by looking at it.
This problem is easy to understand if you think about the right side and the left side separately, because you can flip each child and below and swap the right and left children at the end.
I wrote it with common recursion.
# 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 invertTree(self, root: TreeNode) -> TreeNode:
if not root:
return None
right = self.invertTree(root.right)
left = self.invertTree(root.left)
root.left = right
root.right = left
return root
# Runtime: 28 ms, faster than 74.30% of Python3 online submissions for Invert Binary Tree.
# Memory Usage: 13.8 MB, less than 5.41% of Python3 online submissions for Invert Binary Tree.
Sometimes it's okay to finish quickly like this. I think it's good for practicing trees, so please try to solve it.
Recommended Posts