leetcode:二进制的直径
此代码可适用于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
Question is as follows:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论