二叉树题目集锦

104. 二叉树的最大深度

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7],

1
2
3
4
5
  3
/ \
9 20
/ \
15 7

返回它的最大深度 3 。

1
2
3
4
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root: return 0
return max(self.maxDepth(root.left),self.maxDepth(root.right)) + 1

101. 对称二叉树

给你一个二叉树的根节点 root , 检查它是否轴对称。

示例 1:

1
2
输入:root = [1,2,2,3,4,4,3]
输出:true
1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if root == None: return True
return self.check(root.left, root.right)

def check(self, left: TreeNode, right: TreeNode):
if left == None and right == None: return True
elif left == None and right != None: return False
elif left != None and right == None: return False
elif left.val != right.val: return False

return self.check(left.left, right.right) and self.check(left.right, right.left)

226. 翻转二叉树

给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。

1
2
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]
1
2
3
4
5
6
7
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if not root: return root
root.left,root.right = root.right, root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root

112. 路径总和

给你二叉树的根节点 root 和一个表示目标和的整数 targetSum 。判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum 。如果存在,返回 true ;否则,返回 false 。注意:叶子节点 是指没有子节点的节点。

1
2
3
输入:root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
输出:true
解释:等于目标和的根节点到叶节点路径如上图所示。
1
2
3
4
5
6
7
8
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if root is None: return False
if not root.left and not root.right: return root.val == targetSum
sum = targetSum - root.val
left = self.hasPathSum(root.left,sum)
right = self.hasPathSum(root.right,sum)
return left or right

113. 路径总和 II

给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。叶子节点 是指没有子节点的节点。

1
2
输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
输出:[[5,4,11,2],[5,8,4,5]]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:

res = []
if not root: return res
def helper(node,cursum,path):
if not node.left and not node.right:
if cursum == targetSum:
res.append(path)
if node.left:
helper(node.left,cursum + node.left.val,path + [node.left.val])
if node.right:
helper(node.right,cursum + node.right.val,path + [node.right.val])
helper(root,root.val,[root.val])
return res

236. 二叉树的最近公共祖先

给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

示例 1:

1
2
3
输入:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
输出:3
解释:节点 5 和节点 1 的最近公共祖先是节点 3

示例 2:

1
2
3
输入:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
输出:5
解释:节点 5 和节点 4 的最近公共祖先是节点 5 。因为根据定义最近公共祖先节点可以为节点本身。

分析:设 lca_node 为节点 p、q 的最近公共祖先。则 lca_node 只能是下面几种情况:

  • p、q 在 lca_node 的子树中,且分别在 lca_node 的两侧子树中。
  • p = lca_node,且 q 在 lca_node 的左子树或右子树中。
  • q = lca_node,且 p 在 lca_node 的左子树或右子树中。

具体思路为:

    1. 如果当前节点 node 为 None,则说明 p、q 不在 node 的子树中,不可能为公共祖先,直接返回 None。
    1. 如果当前节点 node 等于 p 或者 q,那么 node 就是 p、q 的最近公共祖先,直接返回 node
    1. 递归遍历左子树、右子树,并判断左右子树结果。
    • (1). 如果左子树为空,则返回右子树。
    • (2). 如果右子树为空,则返回左子树。
    • (3). 如果左右子树都不为空,则说明 p、q 在当前根节点的两侧,当前根节点就是他们的最近公共祖先。
    • (4). 如果左右子树都为空,则返回空。
1
2
3
4
5
6
7
8
9
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root: return None
if root==p or root==q: return root
node_left = self.lowestCommonAncestor(root.left,p,q)
node_right = self.lowestCommonAncestor(root.right,p,q)
if node_left and node_right: return root
elif not node_left: return node_right
else: return node_left

297. 二叉树的序列化与反序列化

设计一个算法,来实现二叉树的序列化与反序列化。

分析:

序列化:将二叉树转为字符串数据表示。按照前序递归遍历二叉树,并将根节点跟左右子树的值链接起来(中间用 , 隔开)。注意:如果遇到空节点,则标记为 ‘None’,这样在反序列化时才能唯一确定一棵二叉树。

反序列化:将字符串数据转为二叉树结构。先将字符串按 , 分割成数组。然后递归处理每一个元素。

  • 从数组左侧取出一个元素。
    • 如果当前元素为 ‘None’,则返回 None。
    • 如果当前元素不为空,则新建一个二叉树节点作为根节点,保存值为当前元素值。并递归遍历左右子树,不断重复从数组中取出元素,进行判断。
    • 最后返回当前根节点。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Codec:

def serialize(self, root):
"""Encodes a tree to a single string.

:type root: TreeNode
:rtype: str
"""
if not root: return 'None'
return str(root.val) + ',' + str(self.serialize(root.left)) + ',' + str(self.serialize(root.right))



def deserialize(self, data):
"""Decodes your encoded data to tree.

:type data: str
:rtype: TreeNode
"""
def dfs(datalist):
val = datalist.pop(0)
if val == 'None':
return None
root = TreeNode(int(val))
root.left = dfs(datalist)
root.right = dfs(datalist)
return root

datalist = data.split(',')
return dfs(datalist)