leetcode:二进制的直径

发布于 2025-02-08 12:18:58 字数 1276 浏览 1 评论 0原文

此代码可适用于100/104测试用例。但是我不知道为什么以及在剩下的4个案例中未能合并代码。请在本文中找到问题和错误情况的图像。

# 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:
        left_root = root.left   # left root of the root node
        right_root = root.right # right side of the root node
        
        def dfs(root: Optional[TreeNode]) -> int: # to calculate the height
            if not root:
                return 0
            
            left = dfs(root.left)
            right = dfs(root.right)
            
            return 1 + max(left, right)
        
        left_depth = dfs(left_root) # finding depth for both sides of it
        right_depth = dfs(right_root)
        
        return left_depth + right_depth # adding the heights

问题如下:

”这是问题“

This code runs correctly for 100/104 test cases. but i dont know why and where does the code fail to incorporate for the remaining 4 cases. Please find the image of the problem and error case in this post.

# 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:
        left_root = root.left   # left root of the root node
        right_root = root.right # right side of the root node
        
        def dfs(root: Optional[TreeNode]) -> int: # to calculate the height
            if not root:
                return 0
            
            left = dfs(root.left)
            right = dfs(root.right)
            
            return 1 + max(left, right)
        
        left_depth = dfs(left_root) # finding depth for both sides of it
        right_depth = dfs(right_root)
        
        return left_depth + right_depth # adding the heights

Error is shown here

Question is as follows:

this is the question

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文