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

Skip to content

Update 543-Diameter-of-Binary-Tree.py #482

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Aug 8, 2022
Merged

Update 543-Diameter-of-Binary-Tree.py #482

merged 8 commits into from
Aug 8, 2022

Conversation

flonle
Copy link
Contributor

@flonle flonle commented Jul 13, 2022

The original return -1 and 2+ actually cancel each other out and thus serve no purpose, only causing confusion.

The original `return -1` and `2+` actually cancel each other out and thus serve no purpose.
@anandbaburajan
Copy link
Contributor

@MeViMo nice! What do you think about changing the res variable from a list to an int, and making it nonlocal inside the dfs function? I found it confusing and was going to open a PR but decided to comment here instead since you already have a PR for the same problem.

# 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:
        res = 0
        
        def dfs(root: Optional[TreeNode]):
            nonlocal res

            if not root:
                return 0
            
            left = dfs(root.left)
            right = dfs(root.right)
            
            res = max(res, left + right)
            
            return 1 + max(left, right)
        
        dfs(root)
        
        return res

@flonle
Copy link
Contributor Author

flonle commented Jul 26, 2022

@anandbaburajan That's probably what I would do to. You can push that change to this PR if you like. Up to the maintainers whether or not to include it.

@anandbaburajan
Copy link
Contributor

I can push the changes but I think you need to resolve the conflicts first.

@flonle
Copy link
Contributor Author

flonle commented Jul 27, 2022

I don't need to but I did for your convenience.

flonle and others added 6 commits July 27, 2022 10:58
Nowhere else in the repo are nested functions annotated so I guess we don't do it here either.
543-Diameter-of-Binary-Tree.py: Use nonlocal res instead of using a list
@Ahmad-A0
Copy link
Collaborator

Ahmad-A0 commented Aug 8, 2022

Thanks, @MeViMo and @anandbaburajan!

@Ahmad-A0 Ahmad-A0 merged commit 6aecc8c into neetcode-gh:main Aug 8, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants