本文主要是介绍小黑隔离日期被多次刷新,深感绝望,得亏阿黄能陪我几天的leetcode之旅:226. 翻转二叉树,257. 二叉树的所有路径,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
226. 翻转二叉树
小黑做法
# 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: Optional[TreeNode]) -> Optional[TreeNode]:# 递归函数def dfs(node):if not node:return Nonenode.left,node.right = node.right,node.leftdfs(node.left)dfs(node.right)dfs(root)return root
层次遍历法
# 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: Optional[TreeNode]) -> Optional[TreeNode]:if not root:return# 初始化队列q = collections.deque([root])while q:# 根结点出队列top = q.popleft()# 交换操作top.left, top.right = top.right, top.leftif top.left:q.append(top.left)if top.right:q.append(top.right)return root
257. 二叉树的所有路径
小黑做法
# 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 binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:if not root:return []self.paths = []def dfs(node, path):# 递归出口if not (node.left or node.right):self.paths.append(''.join(path))# 遍历左子树if node.left:path.append('->'+str(node.left.val))dfs(node.left,path)# 左子树结点poppath.pop()# 遍历右子树if node.right:path.append('->'+str(node.right.val))dfs(node.right,path)# 右子树结点poppath.pop()dfs(root,[str(root.val)])return self.paths
层次遍历
# 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 binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:if not root:return []# 初始化队列q = collections.deque([root])q_str = collections.deque([str(root.val)])paths = []while q:# 出队top = q.popleft()top_str = q_str.popleft()# 输出路径字符串if not (top.left or top.right):paths.append(top_str)continueif top.left:q_str.append(top_str+'->'+str(top.left.val))q.append(top.left)if top.right:q.append(top.right)q_str.append(top_str+'->'+str(top.right.val))return paths
小黑生活
包皮又出血了,命途多舛的手术啊,别人一个星期好了,我又重新打了一圈麻药重新做了个手术,被拉出去隔离了
工作的继续受挫,连着两个岗位被拒,一个初筛没过,小黑陷入了崩溃
隔离与看病生活
阿黄来陪我啦!!!!
准备泡面啦,111宿舍(富河园校区分舍)进行秘密会议
这篇关于小黑隔离日期被多次刷新,深感绝望,得亏阿黄能陪我几天的leetcode之旅:226. 翻转二叉树,257. 二叉树的所有路径的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!