From a3fac8be2bf092fab2423353b7899691672a999e Mon Sep 17 00:00:00 2001 From: 1334monika <92110926+1334monika@users.noreply.github.com> Date: Thu, 24 Oct 2024 20:00:10 +0530 Subject: [PATCH] diameter of BTree (#355) Co-authored-by: 1334monika --- Python/diameterBineryTree.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Python/diameterBineryTree.py diff --git a/Python/diameterBineryTree.py b/Python/diameterBineryTree.py new file mode 100644 index 0000000..0954907 --- /dev/null +++ b/Python/diameterBineryTree.py @@ -0,0 +1,33 @@ +#Function to find the diameter of the given binary tree. + + +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: TreeNode) -> int: + # Initialize the diameter + self.diameter = 0 + + def depth(node: TreeNode) -> int: + # If the node is None, return 0 (base case for leaf nodes) + if not node: + return 0 + + # Recursively find the depth of the left and right subtree + left_depth = depth(node.left) + right_depth = depth(node.right) + + # The diameter at this node is the sum of the left depth and right depth + self.diameter = max(self.diameter, left_depth + right_depth) + + # Return the height of the current node + return max(left_depth, right_depth) + 1 + + # Start the depth-first search from the root + depth(root) + + return self.diameter