# Definition for a binary tree node. classTreeNode: def__init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right
# Definition for a binary tree node. classTreeNode: def__init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right
classSolution: deflevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: ifnot root: return [] queue, cur_level_ans,ans = [root], [], [] while queue: tmp = [] for node in queue: if node.left: tmp.append(node.left) if node.right: tmp.append(node.right) cur_level_ans.append(node.val) queue = tmp ans.append(cur_level_ans) cur_level_ans = [] return ans
classSolution: defcountSubstrings(self, s: str) -> int: n, ans = len(s), 0 for i inrange(n): ans += self.check(i, i, s) ans += self.check(i, i+1, s) return ans defcheck(self, left, right, s): ans = 0 while left >= 0and right <= len(s)-1and s[left] == s[right]: ans += 1 left -= 1 right += 1 return ans
classSolution: defimageSmoother(self, img: List[List[int]]) -> List[List[int]]: m, n = len(img), len(img[0]) ans = [[0for _ inrange(n)] for _ inrange(m)] directions = [-1, 0, 1] for i inrange(m): for j inrange(n): count = 0 total = 0 for row in directions: for col in directions: if0 <= i+row <= m-1and0 <= j+col <= n-1: total += img[i+row][j+col] count += 1 average = total // count ans[i][j] = average return ans
# 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
# 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
# BFS classSolution: defmaxDepth(self, root: Optional[TreeNode]) -> int: ifnot root: return0 queue, res = [root], 0 while queue: tmp = [] for node in queue: if node.left: tmp.append(node.left) if node.right: tmp.append(node.right) queue = tmp res += 1 return res