Maximum Depth of Binary Tree
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 is3
.
递归
树遍历的题最方便的写法自然是递归,不过递归调用的层数过多可能会导致栈空间溢出,因此需要适当考虑递归调用的层数。我们首先来看看使用递归如何解这道题,要求二叉树的最大深度,直观上来讲使用深度优先搜索判断左右子树的深度孰大孰小即可,从根节点往下一层树的深度即自增1,遇到NULL
时即返回0。
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
return 1+max(self.maxDepth(root.left), self.maxDepth(root.right))
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
left = self.maxDepth(root.left)
right = self.maxDepth(root.right)
return max(left, right)+1
由于对每个节点都会使用一次maxDepth
,故时间复杂度为 O(n), 树的深度最大为 n, 最小为 log2n, 故空间复杂度介于 O(logn) 和 O(n) 之间
非递归 :level order
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
level =[root]
h = 0
while level:
nextlevel = []
while level:
node = level.pop()
if node.left:
nextlevel.append(node.left)
if node.right:
nextlevel.append(node.right)
level = nextlevel
h += 1
return h
Last updated
Was this helpful?