Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 515f1bf

Browse files
authored
Merge pull request #3 from AnandBaburajan/patch-1
543-Diameter-of-Binary-Tree.py: Use nonlocal res instead of using a list
2 parents 5d60667 + 1ba4975 commit 515f1bf

File tree

1 file changed

+6
-4
lines changed

1 file changed

+6
-4
lines changed

python/543-Diameter-of-Binary-Tree.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,17 +5,19 @@
55
# self.left = left
66
# self.right = right
77
class Solution:
8-
def diameterOfBinaryTree(self, root: TreeNode) -> int:
9-
res = [0]
8+
def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
9+
res = 0
1010

1111
def dfs(root):
12+
nonlocal res
13+
1214
if not root:
1315
return 0
1416
left = dfs(root.left)
1517
right = dfs(root.right)
16-
res[0] = max(res[0], left + right)
18+
res = max(res, left + right)
1719

1820
return 1 + max(left, right)
1921

2022
dfs(root)
21-
return res[0]
23+
return res

0 commit comments

Comments
 (0)