The problem is to find the diameter of a binary tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
Function Signature:
def diameterOfBinaryTree(root: TreeNode) -> int:
Example: Given a binary tree:
1
/ \
2 3
/ \
4 5
The longest path is [4, 2, 1, 3]
or [5, 2, 1, 3]
, and the length of this path is 3.
depth(node)
that computes the depth of the tree originating from the given node
.depth(node)
, compute the depths of the left and right children.1 + max(depth of left child, depth of right child)
.diameterOfBinaryTree
will initialize the maximum diameter and invoke the helper function starting from the root.class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def diameterOfBinaryTree(root: TreeNode) -> int:
# This variable will hold the maximum diameter found
max_diameter = 0
def depth(node):
nonlocal max_diameter
if not node:
return 0
# Compute the depth of left and right subtrees
left_depth = depth(node.left)
right_depth = depth(node.right)
# Compute the potential diameter at this node
max_diameter = max(max_diameter, left_depth + right_depth)
# Return the depth of this node
return 1 + max(left_depth, right_depth)
# Start the depth computation from the root
depth(root)
return max_diameter
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?