-
Notifications
You must be signed in to change notification settings - Fork 303
Expand file tree
/
Copy path111_minDepth.py
More file actions
44 lines (38 loc) · 1.19 KB
/
111_minDepth.py
File metadata and controls
44 lines (38 loc) · 1.19 KB
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 *
# ****************
class Solution(object):
def minDepth(self, root):
if not root:
return 0
if not root.left or not root.right:
return max(self.minDepth(root.left), self.minDepth(root.right)) + 1
return min(self.minDepth(root.left), self.minDepth(root.right))+ 1
# 底下这个方法其实更好理解,Final的方法刚开始看别人写没看懂,是底下这种方法的改良
# ***************
# Older Version *
# ***************
class Solution(object):
def minDepth(self, root):
if not root:
return 0
if not root.left:
return self.minDepth(root.right) + 1
if not root.right:
return self.minDepth(root.left) + 1
else:
return min(self.minDepth(root.left), self.minDepth(root.right))+ 1