LeetCode

来源:互联网 发布:大数据是以hadoop 编辑:程序博客网 时间:2024/05/29 07:41

Q:
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.

A:

# Definition for a binary tree node.class TreeNode(object):    def __init__(self, x):        self.val = x        self.left = None        self.right = Noneclass Solution(object):    def maxDepth(self, root):        """        :type root: TreeNode        :rtype: int        """        if not root:            return 0        leftDep = self.maxDepth(root.left) + 1        rightDep = self.maxDepth(root.right) + 1        return leftDep if leftDep >= rightDep else rightDep