-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path543.py
More file actions
36 lines (27 loc) · 843 Bytes
/
543.py
File metadata and controls
36 lines (27 loc) · 843 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
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def diameterOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
global ans
ans = 0
def traverse(node):
left_path = 0
right_path = 0
global ans
if node.left is not None:
left_path = traverse(node.left)
if node.right is not None:
right_path = traverse(node.right)
if left_path + right_path > ans:
ans = left_path + right_path
return max(left_path, right_path) + 1
traverse(root)
return ans