-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaxDepth(tree).py
39 lines (34 loc) · 1000 Bytes
/
maxDepth(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
from collections import deque
def maxDepthLv(root):
max_depth = 0
if root is None:
return max_depth
q = deque()
q.append((root, 1))
while q:
cur_node, cur_depth = q.popleft()
max_depth = max(max_depth, cur_depth);
if cur_node.left:
q.append((cur_node.left, cur_depth + 1))
if cur_node.right:
q.append((cur_node.right, cur_depth + 1))
return max_depth;
def maxDepthPost(root):
max_depth = 0
if root is None:
return max_depth
left_depth = maxDepthPost(root.left)
right_depth = maxDepthPost(root.right)
max_depth = max(left_depth,right_depth) + 1;
return max_depth
class TreeNode:
def __init__(self, l = None, r = None , v = 0):
self.left = l
self.right = r
self.value = v
root = TreeNode(v = 3)
root.left = TreeNode(v=9)
root.right = TreeNode(v=20)
root.right.left = TreeNode(v=15)
root.right.right = TreeNode(v=7)
print(maxDepthPost(root))