1.二叉树的定义
二叉树有两种存储方式:顺序存储(数组),链式存储。这里是链式存储的二叉树节点的定义方式。
# 链式存储
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
2.二叉树的遍历
递归遍历
递归三要素:参数与返回值、终止条件、单层逻辑。
# 递归遍历
class Solution:
# 递归前序遍历(leetcode 144.二叉树的前序遍历)
def preorderTraversal(self, root: TreeNode) -> List[int]:
result = []
def traversal(root: TreeNode):
if root == None:
return None
result.append(root.val)
traversal(root.left)
traversal(root.right)
traversal(root)
return result
# 递归中序遍历(leetcode 94.二叉树的中序遍历)
def inorderTraversal(self, root:TreeNode) -> List[int]:
result = []
def traversal(root:TreeNode):
if root == None:
return None
traversal(root.left)
result.append(root.val)
traversal(root.right)
traversal(root)
return result
# 递归后序遍历(leetcode 145.二叉树的后序遍历)
def postorderTraversal(self, root:TreeNode) -> List[int]:
result = []
def traversal(root:TreeNode):
if root == None:
return None
traversal(root.left)
traversal(root.right)
result.append(root.val)
traversal(root)
return result
迭代遍历
统一迭代法:(以前序为例,中左右)
1.将根节点压栈
2.读取栈头节点:右左中空
若不为空,出栈,非空右节点压栈,非空左节点压栈,未读根节点压栈,空节点压栈;
若为空,空节点出栈,未读根节点出栈,读数
3.循环2直到栈为空
同理,中序左中右->右中空左;后序左右中->中空右左
class Solution:
# 统一迭代前序遍历(leetcode 144.二叉树的前序遍历)
def preorderTraversal(self, root: TreeNode) -> List[int]:
result = []
if root == None:
return []
stack = [root]#非空根节点压栈
while stack:
t = stack[-1]#读取栈头
if t != None:
stack.pop()#出栈
if t.right: stack.append(t.right)#右
if t.left: stack.append(t.left)#左
stack.append(t)#中
stack.append(None)#空
else:
stack.pop()#空节点出栈
t = stack.pop()#读取待处理节点并出栈
result.append(t.val)#读数
return result
# 统一迭代中序遍历(leetcode 94.二叉树的中序遍历)
def inorderTraversal(self, root:TreeNode) -> List[int]:
result = []
if root == None: return []
stack = [root]
while stack:
t = stack[-1]
if t:
stack.pop()
if t.right: stack.append(t.right)#右
stack.append(t)#中
stack.append(None)#空
if t.left: stack.append(t.left)#左
else:
stack.pop()
t = stack.pop()
result.append(t.val)
return result
# 统一迭代后序遍历(leetcode 145.二叉树的后序遍历)
def postorderTraversal(self, root:TreeNode) -> List[int]:
result = []
if root == None: return []
stack = [root]
while stack:
t = stack[-1]
if t:
stack.pop()
stack.append(t)#中
stack.append(None)#空
if t.right: stack.append(t.right)#右
if t.left: stack.append(t.left)#左
else:
stack.pop()
t = stack.pop()
result.append(t.val)
return result
层序遍历
广度优先搜索 队列:
1.根节点入队
2.记录当前队列长度,遍历该长度内每一个节点(读数、非空左节点入队、非空右节点入队),此行结果加入结果集
3,重复2直至队列为空。
102.二叉树的层序遍历
# 102.二叉树的层序遍历
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if root == None: return []
results = []
que = deque([root])
while que:
result = []
size = len(que)
for _ in range(size):
t = que.popleft()
result.append(t.val)
if t.left: que.append(t.left)
if t.right: que.append(t.right)
results.append(result)
return results
# 107.二叉树的层序遍历II
class Solution:
def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
if root == None: return []
results = []
que = deque([root])
while que:
result = []
size = len(que)
for _ in range(size):
t = que.popleft()
result.append(t.val)
if t.left: que.append(t.left)
if t.right: que.append(t.right)
results.append(result)
results.reverse()#反转102结果即可
return results
class Solution:
# 199.二叉树的右视图
def rightSideView(self, root: TreeNode) -> List[int]:
if root == None: return []
results = []
que = deque([root])
while que:
result = []
size = len(que)
for _ in range(size):
t = que.popleft()
result.append(t.val)
if t.left: que.append(t.left)
if t.right: que.append(t.right)
results.append(result[-1])#只加最后一个节点数
return results
class Solution:
# 637.二叉树的层平均值
def averageOfLevels(self, root: TreeNode) -> List[int]:
if root == None: return []
results = []
que = deque([root])
while que:
sum = 0
size = len(que)
for _ in range(size):
t = que.popleft()
sum += t.val
if t.left: que.append(t.left)
if t.right: que.append(t.right)
results.append(sum/size)
return results
class Solution:
# 429.N叉树的层序遍历
def levelOrder(self, root: 'Node') -> List[List[int]]:
results = []
if root == None: return []
que = deque([root])
while que:
size = len(que)
result = []
for _ in range(size):
t = que.popleft()
result.append(t.val)
if t.children:
que.extend(t.children)
results.append(result)
return results
class Solution:
# 515.在每个树行中找最大值
def largestValues(self, root: Optional[TreeNode]) -> List[int]:
if root == None: return []
results = []
que = deque([root])
while que:
result = []
size = len(que)
for _ in range(size):
t = que.popleft()
result.append(t.val)
if t.left: que.append(t.left)
if t.right: que.append(t.right)
results.append(max(result))
return results
class Solution:
# 116.填充每个节点的下一个右侧节点指针
def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
if root == None: return None
que = deque([root])
while que:
size = len(que)
for i in range(size):
t = que.popleft()
if t.left: que.append(t.left)
if t.right: que.append(t.right)
if i == size-1: break
t.next = que[0]
return root
117.填充每个节点的下一个右侧节点指针II
同116
104.二叉树的最大深度
class Solution:
# 104.二叉树的最大深度
def maxDepth(self, root: Optional[TreeNode]) -> int:
if root == None: return 0
result = 0
que = deque([root])
while que:
result += 1
size = len(que)
for _ in range(size):
t = que.popleft()
if t.left: que.append(t.left)
if t.right: que.append(t.right)
return result
111.二叉树的最小深度
遇到叶子节点则return深度值
class Solution:
# 111.二叉树的最小深度
def minDepth(self, root: Optional[TreeNode]) -> int:
if not root: return 0
que = deque([root])
result = 0
while que:
size = len(que)
result += 1
for _ in range(size):
t = que.popleft()
if t.left==None and t.right==None: return result
if t.left: que.append(t.left)
if t.right: que.append(t.right)
3.翻转二叉树
226.翻转二叉树
交换每一个节点的左右子节点(除中序遍历外均可)
class Solution:
# 226.翻转二叉树
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if root==None: return None
que = deque([root])
while que:
size = len(que)
for _ in range(size):
t = que.popleft()
if t.left: que.append(t.left)
if t.right: que.append(t.right)
t1 = t.left
t.left = t.right
t.right = t1
return root