一、题目描述
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
二、代码实现
方法一、深搜(DFS)
# 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
"""
def dfs(root, dist, res):
if not root.left and not root.left:
res.append(dist)
if root.left:
dfs(root.left, dist + 1, res)
if root.right:
dfs(root.right, dist + 1, res)
if not root: return 0
res = []
dfs(root, 1, res)
return max(res)
方法二、递归
# 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
if root.left or root.right:
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
else: return 1
网友评论