File tree Expand file tree Collapse file tree 1 file changed +19
-13
lines changed
0543-diameter-of-binary-tree Expand file tree Collapse file tree 1 file changed +19
-13
lines changed Original file line number Diff line number Diff line change 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+
713class 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
You can’t perform that action at this time.
0 commit comments