-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDiameterOfBinaryTree.py
35 lines (26 loc) · 1004 Bytes
/
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
33
34
35
"""
Diameter of Binary Tree
EASY (Wed 14 Dec 2022)
https://leetcode.com/problems/diameter-of-binary-tree/
"""
# 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:
if root is None:
return 0
leftHeight = self.getHeight(root.left)
rightHeight = self.getHeight(root.right)
leftDiameter = self.diameterOfBinaryTree(root.left)
rightDiameter = self.diameterOfBinaryTree(root.right)
return max(leftHeight + rightHeight, max(leftDiameter, rightDiameter))
def getHeight(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
leftHeight = self.getHeight(root.left)
rightHeight = self.getHeight(root.right)
return max(leftHeight, rightHeight) + 1