Skip to content

Commit 052b2c6

Browse files
committed
update readme
1 parent ed70451 commit 052b2c6

File tree

1 file changed

+25
-13
lines changed

1 file changed

+25
-13
lines changed
Lines changed: 25 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,34 @@
1-
# Definition for a binary tree node.
2-
# class TreeNode:
3-
# def __init__(self, val=0, left=None, right=None):
4-
# self.val = val
5-
# self.left = left
6-
# self.right = right
1+
# time complexity: O(n)
2+
# space complexity: O(n)
3+
from typing import Optional
4+
5+
6+
class TreeNode:
7+
def __init__(self, val=0, left=None, right=None):
8+
self.val = val
9+
self.left = left
10+
self.right = right
11+
12+
713
class Solution:
814
def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
915
diameter = 0
1016

11-
def longest_path(node: Optional[TreeNode]):
17+
def longestPath(node: Optional[TreeNode]):
1218
if not node:
1319
return 0
1420
nonlocal diameter
15-
left_path = longest_path(node.left)
16-
right_path = longest_path(node.right)
21+
leftPath = longestPath(node.left)
22+
rightPath = longestPath(node.right)
23+
diameter = max(diameter, leftPath + rightPath)
24+
return max(leftPath, rightPath) + 1
25+
26+
longestPath(root)
27+
return diameter
1728

18-
diameter = max(diameter, left_path + right_path)
19-
return max(left_path, right_path) + 1
2029

21-
longest_path(root)
22-
return diameter
30+
root = TreeNode(1)
31+
root.left = TreeNode(2)
32+
root.left.left = TreeNode(4)
33+
root.left.right = TreeNode(5)
34+
root.right = TreeNode(3)

0 commit comments

Comments
 (0)