- Notifications
You must be signed in to change notification settings - Fork 306
/
Copy path111_minDepth.py
44 lines (38 loc) · 1.19 KB
/
111_minDepth.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
40
41
42
43
44
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: Yu Zhou
# ****************
# Descrption:
# 111. Minimum Depth of Binary Tree
# Given a binary tree, find its minimum depth.
# ****************
# 思路:
# 思考四种Case
# 1. 有或者没有Root
# 2. 有root.left,没有root.right
# 3. 有root.right, 没有 root.left
# 4. 两个Children都有
# ****************
# Final Solution *
# ****************
classSolution(object):
defminDepth(self, root):
ifnotroot:
return0
ifnotroot.leftornotroot.right:
returnmax(self.minDepth(root.left), self.minDepth(root.right)) +1
returnmin(self.minDepth(root.left), self.minDepth(root.right))+1
# 底下这个方法其实更好理解,Final的方法刚开始看别人写没看懂,是底下这种方法的改良
# ***************
# Older Version *
# ***************
classSolution(object):
defminDepth(self, root):
ifnotroot:
return0
ifnotroot.left:
returnself.minDepth(root.right) +1
ifnotroot.right:
returnself.minDepth(root.left) +1
else:
returnmin(self.minDepth(root.left), self.minDepth(root.right))+1