Friday, February 22, 2019

LeetCode 111. Minimum Depth of Binary Tree

'''
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
'''
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def helper(self, i, root):
        if self.result == 0 or i < self.result:
            if not root.left and not root.right:
                self.result = i
            else:
                if root.left: self.helper(i+1, root.left)
                if root.right: self.helper(i+1, root.right)
   
    def minDepth(self, root: 'TreeNode') -> 'int':
        self.result = 0
        if root:
            self.helper(1, root)
        return self.result

No comments:

Post a Comment