【力扣hot100】刷题笔记Day12
前言
- 小涛啊小涛,你不能就这么荒废学习安逸享乐!工作找不到啦!
104. 二叉树的最大深度 - 力扣(LeetCode)
226. 翻转二叉树 - 力扣(LeetCode)
-
递归
-
# 后序遍历
class Solution:def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:if not root: returnleftTree = self.invertTree(root.left) # 左rightTree = self.invertTree(root.right) # 右root.left, root.right = rightTree, leftTree # 中return root
# 先序遍历
class Solution:def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:if not root: returnroot.left, root.right = root.right, root.left # 中self.invertTree(root.left) # 左self.invertTree(root.right) # 右return root
-
迭代
-
# 前序遍历
class Solution:def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:if not root: returnst = [root]while st:cur = st.pop()cur.left, cur.right = cur.right, cur.left # 中if cur.right: st.append(cur.right) # 右if cur.left: st.append(cur.left) # 左return root# 层序遍历
class Solution:def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:if not root: returnq = deque()q.append(root)while q:for i in range(len(q)):cur = q.popleft()if cur.left: q.append(cur.left)if cur.right: q.append(cur.right)cur.left, cur.right = cur.right, cur.left # 交换return root
101. 对称二叉树 - 力扣(LeetCode)
-
递归法
-
class Solution:def isSymmetric(self, root: Optional[TreeNode]) -> bool:if not root:return Truedef dfs(left, right):if not left and not right: # 00,都为空return Trueelif not (left and right): # 01和10,一个为空return Falseelif left.val != right.val: # 值不相等return False# 左左右右 and 左右右左return dfs(left.left, right.right) and dfs(left.right, right.left)return dfs(root.left, root.right)
-
迭代
-
class Solution:def isSymmetric(self, root: Optional[TreeNode]) -> bool:if not root or not(root.left or root.right): # root空或者左右为空return True# 用队列保存结点q = [root.left, root.right]while q:# 取出两个结点比较left = q.pop(0)right = q.pop(0)# 都为空则继续,有一个为空或者不对称就返回falseif not (left or right):continueelif not (left and right):return Falseelif left.val != right.val:return False# 下次比较左左右右q.append(left.left)q.append(right.right)# 下下次比较左右右左q.append(left.right)q.append(right.left)# 如果整个队列遍历完了说明完全对称return True
后言
- 这一整天二叉树的,真的学累了,脑子都要叉开了......玩儿去咯
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/699851.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!