Python solution with recursion


  • 0
    L
    # Definition for a  binary tree node
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        # @param root, a tree node
        # @return an integer
        def maxDepth(self, root):
            # depth of a empty tree is 0
            if root == None:
                return 0
                
            # depth of left sub-tree
            left_depth = Solution().maxDepth(root.left)
            # depth of right sub-tree
            right_depth = Solution().maxDepth(root.right)
            
            # depth of binary-tree equals maxDepth of sub-tree add 1(itself)
            return left_depth+1 if left_depth>=right_depth else right_depth+1

  • 2
    Y

    Your last return statement can be replaced by a simpler form:

    return max(left_depth+1, right_depth+1)

  • 0
    H

    The code can be further reduced to 3 lines


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.