Diameter of a Tree
MediumPremium
Given the root of a binary tree, create a function diameterOfTree that determines and returns the length of the diameter of the tree, where the diameter of a tree is defined as the number of nodes along the longest path between any two nodes in the tree.
For example, given the following binary tree:
// tree 1 / \ 2 3 / \ 4 5
The diameter is 4, which is the length of the path [4, 2, 1, 3] or [5, 2, 1, 3].
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def diameterOfTree(root):
def heightOfTree(node, diameter):
if not node:
return 0
leftHeight = heightOfTree(node.left, diameter)
rightHeight = heightOfTree(node.right, diameter)
diameter[0] = max(diameter[0], leftHeight + rightHeight)
return max(leftHeight, rightHeight) + 1
diameter = [0]
heightOfTree(root, diameter)
return diameter[0]Watch Ali, SDE @ Amazon, answer the question: "Given the root of a binary tree, return the length of the diameter of the tree."
Without using a recursive approach, one can perform a post-order traversal by removing the parent nodes from the stack only if children were visited:
def diameterOfTree(root): if root is None: return 0 diameter = 0 stack = deque([[root, False]]) # (node, visited) node_heights = {} while stack: curr_node, visited = stack[-1] if visited: height_left = node_heights.get(curr_node.left, 0) height_right = node_heights.get(curr_node.right, 0) diameter = max(diameter, height_left + height_right) node_heights[curr_node] = max(height_left, height_right) + 1 stack.pop() # a node can be deleted if its leaves were visited else: stack[-1][1] = True if curr_node.left is not None: stack.append([curr_node.left, False]) if curr_node.right is not None: stack.append([curr_node.right, False]) return diameter