
圖1
# 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
if (root.left is None) and (root.right is None):
return 1
depth = maxdepth()
depth.depth(root, 1)
return max(depth.l)
class maxdepth:
def __init__(self):
self.l = []
def depth(self, t, i):
if t.right or t.left:
if t.left:
self.depth(t.left, i+1)
if t.right:
self.depth(t.right, i+1)
else:
self.l.append(i)
return
思路:遍歷每個葉子節(jié)點(diǎn)時,記錄走到葉子節(jié)點(diǎn)的路徑數(shù),放入到列表中,當(dāng)全部遍歷結(jié)束時,找出列表中最大值就是其深度。