1. 题目
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
2. 解题思路
详情见 面试题55 - I. 二叉树的深度(后序遍历、层序遍历,清晰图解)
2.1 递归
从根节点来看,整个树的深度=max(左子树的深度,右子树的深度) + 1,就这样递归下去,递归的基线条件就是节点为None。
2.2 广度优先遍历(BFS)
二叉树有几层深度就是几,所以每有一层深度就加1.
3. 代码实现
3.1 递归
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
l = self.maxDepth(root.left)
r = self.maxDepth(root.right)
return l+1 if l > r else r+1
3.2 BFS
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
"""
什么是二叉树的深度?
每有一层,深度就加1
"""
if not root: return 0
depth = 0
queue = [root]
while queue:
temp = []
for node in queue:
if node.left: temp.append(node.left)
if node.right: temp.append(node.right)
queue = temp
depth += 1
return depth
4. 总结
通常树的问题都可以用递归来解决。
5. 参考文献
[1] 剑指offer丛书
[2] 剑指Offer——名企面试官精讲典型编程题