# Print Binary Tree Diameter Path [duplicate]

Diameter of the tree is defined as a long path or route, between any two nodes in a tree. The path may or may not goes through the ROOT.

Print the Longest leaf to leaf path in a binary tree and its length

I worth an algorithm that calculates the diameter in Swift:

func diameter() -> Int {
return diameterHelper(root).Diameter
}

typealias HeightAndDiameter = (Height: Int, Diameter: Int)

private func diameterHelper(node: TreeNode<T>?) -> HeightAndDiameter {

guard let node = node else {
return HeightAndDiameter(Height:0, Diameter:0)
}

let left  = diameterHelper(node.left)
let right = diameterHelper(node.right)

let height   = max(left.Height, right.Height) + 1
let diameter = max(left.Height + right.Height + 1, max(left.Diameter, right.Diameter))

return HeightAndDiameter(Height: height, Diameter: diameter)
}


I have tried to adapt this algorithm, but it doesn't work for all the cases.

  func diameterPath() -> [T] {
return diameterPathHelper(root).Path
}

typealias HeightAndDiameterAndPath = (Height: Int, Diameter: Int, Path: [T])

private func diameterPathHelper(node: TreeNode<T>?) -> HeightAndDiameterAndPath {

guard let node = node else {
return HeightAndDiameterAndPath(0, 0, [])
}

let left  = diameterPathHelper(node.left)
let right = diameterPathHelper(node.right)

let height = max(left.Height, right.Height) + 1

if left.Height + right.Height + 1 > max(left.Diameter, right.Diameter) {
let currentDiameter = left.Height + right.Height + 1
let path = left.Path + [node.data] + right.Path
return HeightAndDiameterAndPath(height, currentDiameter, path)

} else {
if left.Diameter > right.Diameter {
return HeightAndDiameterAndPath(height, left.Diameter, left.Path)
} else {
return HeightAndDiameterAndPath(height, right.Diameter, right.Path)
}
}
}

• Please replace the code with pseudocode. Your code is hard to read. – Yuval Filmus Jan 24 '16 at 21:06
• See also cs.stackexchange.com/q/22855/755. And for the future: note that coding questions are off-topic here, and not everyone knows Swift; we want you to avoid code and instead present ideas, pseudocode, and proofs. – D.W. Jan 25 '16 at 3:33

## 1 Answer

One natural approach goes as follows. Compute recursively for each node both the longest leaf-to-leaf path in the subtree rooted at the node, and the depth of the deepest leaf. From this information for the two children of a node you can compute the same information for the node itself. Once you have reached the root, you have obtained your answer.

The above only computes the length of the longest path, but you can actually extract the longest path itself from the data for each node. Details left to you.