Print Binary Tree Diameter Path 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() -&gt; Int {
 return diameterHelper(root).Diameter
}

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

private func diameterHelper(node: TreeNode&lt;T&gt;?) -&gt; 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() -&gt; [T] {
    return diameterPathHelper(root).Path
  }

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

  private func diameterPathHelper(node: TreeNode&lt;T&gt;?) -&gt; 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 &gt; 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 &gt; right.Diameter {
        return HeightAndDiameterAndPath(height, left.Diameter, left.Path)
      } else {
        return HeightAndDiameterAndPath(height, right.Diameter, right.Path)
      }
    }
  }
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.