For financial reasons, Doctor and Amiya have to go farm in the rice fields now. The rice fields they have to go through are shaped like a binary tree, can you help them calculate the diameter of the rice fields they have to farm?

The diameter of a tree is the number of edges on the longest path between any two nodes.
0Example A: the longest path passes throught the root
1
/ \
2 3 Longest path: 4 - 2 - 1 - 3 (3 edges)
/ \ Diameter = 3
4 5
Example B: the longest path does not passes throught the root
1
/
2 Longest path: 5 - 3 - 2 - 4 - 6 (4 edges)
/ \ Diameter = 4
3 4
/ \
5 6
Every path has a top node, the node closest to the root. Call it v.
The longest path whose top node is v goes down the deepest branch on each side:
v
/ \
left right
(deepest) (deepest)
Two ways to measure a branch
For a node x , we look at the longest path going down from x. We can measure it in two ways:
| Method | Count | Leaf | Empty Child (None) |
| depth(x) | edges on the path | 0 | -1 |
| height(x) | nodes on the path | 1 | 0 |
They always differ by exactly one: height(x) = depth(x) + 1
1 depth(4) = 0 height(4) = 1
/ \ depth(2) = 1 height(2) = 2
2 3 depth(3) = 0 height(3) = 1
/ depth(1) = 2 height(1) = 3
4
From depth to height
Start with depth, because it counts edges, which is what the diameter measures.
Going from v down the left side, the path uses one edge from v to its left child,
plus depth(left) more edges inside the left subtree. The right side works the same way:
longest path with top node v = (depth(left) + 1) + (depth(right) + 1)
The two +1 are the edges connecting +1 to its children. Now replace depth+1 by height:
longest path with top node v = height(left) + height(right)
From now on, we only use height. So the diameter is the maximum of that value over all nodes:
Visit every node once, from the bottom up (a post-order traversal: handle the left and right subtrees first, then the node itself). At each node v:
1. Get height(left) and height(right) by recursion.
2. Update diameter = max(diameter, height(left)+height(right))
3. Return 1 + max(height(left), height(right)) to the parent.
Each node is visited once, so the running time is O(n).
Given a binary tree, print its diameter (number of edges)
Complete all methods marked with TODO in the provided starter code
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def build_tree(tokens):
"""Build a binary tree from level-order tokens. (Provided, do not modify.)"""
if not tokens or tokens[0] == "null":
return None
root = TreeNode(int(tokens[0]))
queue = [root]
head = 0 # index of the next node to take from the queue
i = 1
while head < len(queue) and i < len(tokens):
node = queue[head]
head += 1
if i < len(tokens) and tokens[i] != "null":
node.left = TreeNode(int(tokens[i]))
queue.append(node.left)
i += 1
if i < len(tokens) and tokens[i] != "null":
node.right = TreeNode(int(tokens[i]))
queue.append(node.right)
i += 1
return root
def diameter_of_binary_tree(root):
"""Return the diameter of the tree, in edges."""
if root is None:
return 0
height = {} # height[node] = number of NODES on the longest downward path
diameter = 0
# Iterative post-order DFS (a recursive one would be too deep for 100000 nodes).
# Each entry on the stack is a pair (node, visited).
stack = [(root, False)]
while stack:
node, visited = stack.pop()
if not visited:
# First time we see this node: come back to it AFTER its children.
stack.append((node, True))
# TODO 1: if the right child exists, push (right child, False).
# TODO 2: if the left child exists, push (left child, False).
else:
# Second time: both children are finished, so their heights are known.
# TODO 3: get the height of the left child (an empty child has height 0).
# Hint: height.get(key, default)
left_h = 0
# TODO 4: get the height of the right child.
right_h = 0
# TODO 5: update `diameter` using the two heights.
# TODO 6: store the height of `node` in height[node].
pass
return diameter
if __name__ == "__main__":
tokens = input().split()
root = build_tree(tokens)
print(diameter_of_binary_tree(root))
One line with the tree in level-order, tokens separated by spaces. Missing children are written a null . A null node has no children listed.
1 2 3 4 5 describes:
1
/ \
2 3
/ \
4 5
1 null 2 3 describes: 1 \ 2 / 3
1 <= number of nodes <= 100000
Node values are integers and do not matter for the answer.
The tree can be very deep (e.g. a chain of 100000 nodes). Use an iterative DFS or raise Python's recursion limit.
One integer: the diameter of the tree (in edges).