Tuesday, October 11, 2016

LeetCode: Find the maximum depth of a Binary Tree

# 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
        """
        '''
        #///////////////////////////
        # recursive implementation
        # Complexity: O(n) - since it has to visit all the nodes
        #///////////////////////////
        if not root:
            return 0
            
        leftHeight = self.maxDepth(root.left)
        rightHeight = self.maxDepth(root.right)
        
        if leftHeight > rightHeight:
            return leftHeight + 1
        else:
            return rightHeight + 1

No comments:

Post a Comment