forked from yanglei-github/Leetcode_in_python3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
104_Maximum Depth of Binary Tree.py
59 lines (51 loc) · 1.54 KB
/
104_Maximum Depth of Binary Tree.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 4 15:26:08 2019
@author: leiya
"""
#dfs或者bfs找到最大层数即是最大深度
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if root is None:
return 0
else:
return max(self.maxDepth(root.left),self.maxDepth(root.right))+1
#updated: 0628
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
queue = [root]
count = 0
while queue:
current_len = len(queue)
count += 1
for _ in range(current_len):
pop_node = queue.pop(0)
if pop_node.left is not None:
queue.append(pop_node.left)
if pop_node.right is not None:
queue.append(pop_node.right)
return count
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if root is None:
return 0
cur_queue = [root]
count = 0
while cur_queue:
next_queue = []
for node in cur_queue:
if node.left is not None:
next_queue.append(node.left)
if node.right is not None:
next_queue.append(node.right)
count += 1
cur_queue = next_queue
return count