-
Notifications
You must be signed in to change notification settings - Fork 0
/
543-DiameterOfBinaryTree.py
32 lines (25 loc) · 1.01 KB
/
543-DiameterOfBinaryTree.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
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
self.diameter = 0
def postOrderTraversal(node):
if node.left is None and node.right is None:
node.llong, node.rlong = 0, 0
return
node.llong = 0
if node.left is not None:
postOrderTraversal(node.left)
node.llong = max(node.left.llong, node.left.rlong) + 1
node.rlong = 0
if node.right is not None:
postOrderTraversal(node.right)
node.rlong = max(node.right.llong, node.right.rlong) + 1
if node.llong + node.rlong > self.diameter:
self.diameter = node.llong + node.rlong
postOrderTraversal(root)
return self.diameter