function diameterOfBinaryTree(root): if root is null: return 0 stack = [] // 用于模拟递归的栈 heightMap = {} // 存储节点高度信息的哈希表 result = 0
stack.push(root) while stack is not empty: node = stack.pop() if node.left is not null: stack.push(node.left) if node.right is not null: stack.push(node.right) leftHeight = 0 rightHeight = 0 if node.left in heightMap: leftHeight = heightMap[node.left] + 1 else: leftHeight = getHeight(node.left) + 1 if node.right in heightMap: rightHeight = heightMap[node.right] + 1 else: rightHeight = getHeight(node.right) + 1 heightMap[node] = max(leftHeight, rightHeight) result = max(result, leftHeight + rightHeight - 2)
return result
function getHeight(node): if node is null: return 0 stack = [] height = 0 stack.push(node) while stack is not empty: current = stack.pop() if current.left is not null: stack.push(current.left) if current.right is not null: stack.push(current.right) height++ return height