二叉树的最大深度

图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

思路:遍历每个叶子节点时,记录走到叶子节点的路径数,放入到列表中,当全部遍历结束时,找出列表中最大值就是其深度。

你可能感兴趣的:(二叉树的最大深度)