-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbin_tree_diam.py
More file actions
86 lines (68 loc) · 2.27 KB
/
Copy pathbin_tree_diam.py
File metadata and controls
86 lines (68 loc) · 2.27 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# Leetcode: https://leetcode.com/problems/diameter-of-binary-tree/description/
# Slow as hell.. I think it's because of the constant recomputation of depth. We technically could merge
# maxDepth and depth into one function. This I believe will increase speeds greatly (it does, see commented)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def diameterOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
mx = 0
return self.maxDepth(root, mx)
def maxDepth(self, root, mx):
if root is None: return mx
left = self.depth(root.left)
right = self.depth(root.right)
# If max left = 1, max right = 5, total = 6 steps
mx = max(mx, left + right)
return max(self.maxDepth(root.left, mx), self.maxDepth(root.right, mx))
def depth(self, root):
if root is None: return 0
return 1 + max(self.depth(root.left), self.depth(root.right))
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
mx = 0
def diameterOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.depth(root)
return self.mx
def depth(self, root):
if root is None: return 0
left = self.depth(root.left)
right = self.depth(root.right)
# If max left = 1, max right = 5, total = 6 steps
self.mx = max(self.mx, left + right)
return 1 + max(left, right)
"""
class Solution(object):
mx = 0
def diameterOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.depth(root)
return self.mx
def depth(self, root):
if root is None: return 0
left = self.depth(root.left)
right = self.depth(root.right)
# If max left = 1, max right = 5, total = 6 steps
self.mx = max(self.mx, left + right)
return 1 + max(left, right)
"""