目录
前言
一、二叉树:二叉树的中序遍历,二叉树的最大深度,翻转二叉树,对称二叉树,二叉树的直径,二叉树的层序遍历,将有序数组转换为二叉搜索树,验证二叉搜索树,二叉搜索树中第 K 小的元素,二叉树的右视图,二叉树展开为链表,从前序与中序遍历序列构造二叉树,路径总和 III,二叉树的最近公共祖先,二叉树中的最大路径和。
二、图论:岛屿数量,腐烂的橘子,课程表,实现 Trie (前缀树)。
一、二叉树
1. 二叉树的深度遍历(DFS:前序、中序、后序遍历)
原题链接:94. 二叉树的中序遍历 - 力扣(LeetCode)

# (1)前序遍历:根-左-右
class Solution(object):
def preorderTraversal(self, root):
res = []
def preorder(root):
if not root:
return
res.append(root.val)
preorder(root.left)
preorder(root.right)
preorder(root)
return res
# (2)中序遍历:左-根-右
class Solution(object):
def inorderTraversal(self, root):
res = []
def inorder(root):
if not root:
return
inorder(root.left)
res.append(root.val)
inorder(root.right)
inorder(root)
return res
# (3)后序遍历:左-右-根
class Solution(object):
def postorderTraversal(self, root):
res = []
def inorder(root):
if not root:
return
postorder(root.left)
postorder(root.right)
res.append(root.val)
postorder(root)
return res
2. 二叉树的最大深度
原题链接:104. 二叉树的最大深度 - 力扣(LeetCode)

class Solution(object):
def maxDepth(self, root):
if not root:
return 0
left_height = self.maxDepth(root.left)
right_height = self.maxDepth(root.right)
return max(left_height, right_height) + 1
3. 翻转二叉树
原题链接:226. 翻转二叉树 - 力扣(LeetCode)

class Solution(object):
def invertTree(self, root):
if not root:
return
root.left, root.right = root.right, root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
4. 对称二叉树
原题链接:101. 对称二叉树 - 力扣(LeetCode)

class Solution(object):
def isSymmetric(self, root):
def check(left, right):
if not left and not right:
return True
if not left or not right:
return False
if left.val != right.val:
return False
return check(left.left, right.right) and check(left.right, right.left)
return check(root.left, root.right)
5. 二叉树的直径
原题链接:

4186

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



