Leetcode树题目相关模板
1. 二叉树深度遍历
1.1 树的递归写法
def dfs(root):
if not root:
return
# 主要逻辑 # 前序遍历
dfs(root.left)
# 主要逻辑 # 中序遍历
dfs(root.right)
# 主要逻辑 # 后序遍历
1.2 将树的递归改为迭代
题目集合:
class Solution:
def inorderTraversal(self, root:TreeNode)->List[int]:
WHITE, GRAY = 0, 1
res = []
stack = [(WHITE,root)]
while stack:
color, node = stack.pop()
if not node:continue
if color == WHITE:
# stack.append((GRAy,node)) # 后序遍历
stack.append((WHITE,node.right))
# stack.append((GRAY, node)) # 中序遍历
stack.append((WHITE, node.left))
# stack.append((GRAy,node)) # 前序遍历
else:
res.append(node.val)
return res
2. 二叉树层次遍历
层序遍历:https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
2.1 递归写法
# 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 levelOrder(self, root: TreeNode) -> List[List[int]]:
"""递归法"""
if root is None:
return []
result = []
def add_to_result(level, node):
"""递归函数
Args:
level:当前二叉树的层次
node: 当前节点
"""
if level > len(result) -1 :
result.append([])
result[level].append(node.val)
if node.left:
add_to_result(level+1, node.left)
if node.right:
add_to_result(level+1, node.right)
add_to_result(0, root)
return result
2.2 迭代写法
def levelOrder(self,root):
if not root:
return
res = []
queue = [root]
while queue:
size = len(queue)
tmp = []
for _ in range(size):
r = queue.pop(0)
tmp.append(r.val)
if r.left:
queue.append(r.left)
if r.rigth:
queue.append(r.right)
res.append(tmp)
return res
3. 构建二叉树
3.1 从前序和中序构造二叉树
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
"""通过前序和中序遍历构造二叉树
前序可以确定根节点,中序可以区分左右子树
Args:
preorder(List[int]):前序遍历
inorder(List[int]): 中序遍历
Returns:
root(TreeNode):根节点
"""
if not preorder:
return
root = TreeNode(preorder[0])
# 题目说明了没有重复元素,因此我们可以通过 val 去 inorder 找到根在 inorder 中的索引 i
i = inorder.index(root.val)
# 对左右子树分别递归构建子树
root.left = self.buildTree(preorder[1:i+1],inorder[:i])
root.right = self.buildTree(preorder[i+1:],inorder[i+1:])
return root
3.2 从中序和后序构造二叉树
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
if not inorder:
return None
root = TreeNode(postorder[-1])
# 获取中序遍历的索引 那么也可以得知左右子树分别有多少个node
i = inorder.index(root.val)
root.left = self.buildTree(inorder[:i],postorder[:i])
root.right = self.buildTree(inorder[i+1:],postorder[i:-1])
return root
3.3 从前序和后序遍历构造二叉树
class Solution:
def constructFromPrePost(self, preorder: List[int], postorder: List[int]) -> TreeNode:
if not preorder:
return None
node = TreeNode(preorder[0])
if len(preorder) ==1 :
return node
# 左子树根节点
i = postorder.index(preorder[1])
node.left = self.constructFromPrePost(preorder[1:i+2], postorder[:i+1])
node.right = self.constructFromPrePost(preorder[i+2:], postorder[i+1:-1])
return node