Complete the code to define the TreeNode class constructor.
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = [1] self.left = left self.right = right
The constructor assigns the input value val to the node's val attribute.
Complete the code to calculate the height of a binary tree node recursively.
def height(node): if not node: return 0 left_height = height(node.left) right_height = height(node.right) return 1 + [1](left_height, right_height)
The height of a node is 1 plus the maximum height of its left and right children.
Fix the error in the recursive diameter calculation by completing the return statement.
def diameter(node): if not node: return 0 left_height = height(node.left) right_height = height(node.right) left_diameter = diameter(node.left) right_diameter = diameter(node.right) return max(left_height + right_height, [1](left_diameter, right_diameter))
The diameter is the maximum of the path through the root and the largest diameter in the subtrees.
Fill both blanks to complete the optimized diameter calculation using a helper function that returns height and diameter.
def diameter_helper(node): if not node: return (0, 0) # height, diameter left_height, left_diameter = diameter_helper(node.left) right_height, right_diameter = diameter_helper(node.right) current_height = 1 + [1](left_height, right_height) current_diameter = max(left_height + right_height, [2](left_diameter, right_diameter)) return (current_height, current_diameter)
Height is 1 plus max of left and right heights. Diameter is max of path through root and largest subtree diameter.
Fill all three blanks to complete the main function that returns the diameter of the binary tree.
def diameter_of_binary_tree(root): def helper(node): if not node: return (0, 0) # height, diameter left_height, left_diameter = helper(node.left) right_height, right_diameter = helper(node.right) current_height = 1 + [1](left_height, right_height) current_diameter = max(left_height + right_height, [2](left_diameter, right_diameter)) return (current_height, current_diameter) return [3](root)[1]
The helper function calculates height and diameter recursively. The main function returns the diameter part of the tuple.
