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.
Basically, I would like to solve the easy acceptance in descending order.
Last time Leet Code Day8 starting from zero "1302. Deepest Leaves Sum"
701. Insert into a Binary Search Tree
It's a problem of trees and a problem that can be seen from the title again.
As you can see, we are given a binary search tree, so the problem is to insert the numbers correctly into that tree and return the inserted tree.
# 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 insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
if root is None:
return TreeNode(val)
if root.val > val:
root.left = self.insertIntoBST(root.left, val)
elif root.val < val:
root.right = self.insertIntoBST(root.right, val)
return root
# Runtime: 124 ms, faster than 99.95% of Python3 online submissions for Insert into a Binary Search Tree.
# Memory Usage: 15.9 MB, less than 8.00% of Python3 online submissions for Insert into a Binary Search Tree.
Using the property of the binary search tree, the value of val of root is compared with val, and if root is larger, recursive processing is performed to the left, otherwise to the right, and when the processing is completed, root is processed. I wrote a simple one that returns. It's a simpler answer than I thought before writing.
Recommended Posts