-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiameter_binary_tree.py
More file actions
45 lines (35 loc) · 863 Bytes
/
diameter_binary_tree.py
File metadata and controls
45 lines (35 loc) · 863 Bytes
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
import sys
# https://leetcode.com/problems/diameter-of-binary-tree/
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def diameterOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.maxPathLen = 0
self.findMaxPaths(root)
return self.maxPathLen
def findMaxPaths(self, root):
if root is None:
return 0
if root.left is None and root.right is None:
return 0
leftLen = 0
if root.left is not None:
leftLen = self.findMaxPaths(root.left) + 1
rightLen = 0
if root.right is not None:
rightLen = self.findMaxPaths(root.right) + 1
if leftLen + rightLen > self.maxPathLen:
self.maxPathLen = leftLen + rightLen
return max(leftLen, rightLen)
def main():
str = input('input: ')
output = function(str)
print('output: ', output)
if __name__ == '__main__':
main()