Maximum Depth of Binary Tree
Question
- leetcode: Maximum Depth of Binary Tree | LeetCode OJ
- lintcode: (97) Maximum Depth of Binary Tree
Problem Statement
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Example
Given a binary tree as follow:
1
/ \
2 3
/ \
4 5
The maximum depth is 3
.
题解 - 递归
树遍历的题最方便的写法自然是递归,不过递归调用的层数过多可能会导致栈空间溢出,因此需要适当考虑递归调用的层数。我们首先来看看使用递归如何解这道题,要求二叉树的最大深度,直观上来讲使用深度优先搜索判断左右子树的深度孰大孰小即可,从根节点往下一层树的深度即自增1,遇到NULL
时即返回0。
由于对每个节点都会使用一次maxDepth
,故时间复杂度为 $$O(n)$$, 树的深度最大为 $$n$$, 最小为 $$\log_2 n$$, 故空间复杂度介于 $$O(\log n)$$ 和 $$O(n)$$ 之间。
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return an integer
def maxDepth(self, root):
if root == None:
return 0
else:
return max( self.maxDepth(root.left), self.maxDepth(root.right) ) + 1
题解 - 迭代(显式栈)
使用递归可能会导致栈空间溢出,这里使用显式栈空间(使用堆内存)来代替之前的隐式栈空间。从上节递归版的代码(先处理左子树,后处理右子树,最后返回其中的较大值)来看,是可以使用类似后序遍历的迭代思想去实现的。
首先使用后序遍历的模板,在每次迭代循环结束处比较栈当前的大小和当前最大值max_depth
进行比较。
题解3 - 迭代(队列)
在使用了递归/后序遍历求解树最大深度之后,我们还可以直接从问题出发进行分析,树的最大深度即为广度优先搜索中的层数,故可以直接使用广度优先搜索求出最大深度。