-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathanswer.py
39 lines (34 loc) · 1.43 KB
/
answer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/usr/bin/env python
#-------------------------------------------------------------------------------
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
#-------------------------------------------------------------------------------
# Clean Solution
#-------------------------------------------------------------------------------
def minDepth(self, root):
if root == None:
return 0
if root.left==None or root.right==None:
return self.minDepth(root.left)+self.minDepth(root.right)+1
return min(self.minDepth(root.right),self.minDepth(root.left))+1
#-------------------------------------------------------------------------------
# Less optimal/clean solution
#-------------------------------------------------------------------------------
def minDepth2(self, root):
if root:
return self.help(root, 1)
return 0
def help(self, root, count):
if root is None:
# Probably a bad way to do this lol
return 99999999
if root.left is None and root.right is None:
return count
return min(self.help(root.left, count+1), self.help(root.right, count+1))
#-------------------------------------------------------------------------------
# Testing