102. 二叉树的层序遍历
二叉树层序遍历:队列
python的collection包中有队列
import collections
queue = collections.deque()
queue.append(root)
queue.appendleft('b')
queue.extend(['c','d']) # 在最右边添加所有元素,这里就是一行代码添加c,d
queue.pop() # 将最右边的元素取出
queue.popleft()
104. 二叉树的最大深度
做树的题目,要能把问题看成子树的问题,自己总是写回溯,但其实用递归就可以
# 自己写的
class Solution:
def maxDepth(self, root: TreeNode) -> int:
m = 0
def dfs(root, n):
nonlocal m
if root:
n += 1
dfs(root.left, n)
dfs(root.right, n)
n -= 1
else:
m = max(m, n)
return
dfs(root, 0)
return m
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
return max(self.maxDepth(root.left)+1,self.maxDepth(root.right)+1)
# 作者:superpeak-6
# 链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/solution/python-bi-jiao-jian-dan-de-shen-du-bian-li-jie-fa-/
# 来源:力扣(LeetCode)
# 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
105. 从前序与中序遍历序列构造二叉树
步骤:
1.将当前前序遍历的第一个节点作为根节点,建立节点(递归函数传递的是节点在前序遍历中的位置而不是前序切片)
2.在中序遍历中找到该节点,得到该节点的左子树size_left_subtree和右子树,包括他们的节点的数目
3.先序遍历中「从 左边界+1 开始的 size_left_subtree」个元素就对应了中序遍历中「从 左边界 开始到 根节点定位-1」的元素,递归构造左子树,连接到根节点
4.先序遍历中「从 左边界+1+ size_left_subtree 开始到 右边界」的元素就对应了中序遍历中「从 根节点定位+1 到 右边界」的元素,递归构建右子树,连接到根节点
5.如果当前先序遍历左索引大于右索引,终止
109. 有序链表转换二叉搜索树
链表快慢指针找重点
快指针每次移动两步,慢指针每次移动一步
def findmid(head, tail):
slow = head
fast = head
while fast != tail and fast.next != tail:
slow = slow.next
fast = fast.next.next
return slow
389




被折叠的 条评论
为什么被折叠?



