Skip to content

Commit 48aa0e7

Browse files
committed
Sync LeetCode submission Runtime - 8 ms (22.94%), Memory - 20.9 MB (5.81%)
1 parent 2d76a3f commit 48aa0e7

File tree

1 file changed

+19
-13
lines changed

1 file changed

+19
-13
lines changed
Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,31 @@
1+
# Approach 1: Depth First Search
2+
3+
# Time: O(n)
4+
# Space: O(n)
5+
16
# Definition for a binary tree node.
27
# class TreeNode:
38
# def __init__(self, val=0, left=None, right=None):
49
# self.val = val
510
# self.left = left
611
# self.right = right
12+
713
class Solution:
814
def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
9-
diameter = 0
10-
11-
def find_longest_path(node):
12-
nonlocal diameter
15+
diameter = 0
16+
17+
def longest_path(node):
1318
if not node:
1419
return 0
15-
16-
left_path = find_longest_path(node.left)
17-
right_path = find_longest_path(node.right)
18-
19-
diameter = max(diameter, left_path+right_path)
20-
21-
return max(left_path, right_path)+1
22-
23-
find_longest_path(root)
20+
nonlocal diameter
21+
22+
left_path = longest_path(node.left)
23+
right_path = longest_path(node.right)
24+
25+
diameter = max(diameter, left_path + right_path)
26+
27+
return max(left_path, right_path) + 1
28+
29+
longest_path(root)
2430
return diameter
2531

0 commit comments

Comments
 (0)