# Program to find longest path between two nodes of a tree in Python

Suppose we have a binary tree; we have to find the longest path between any two nodes in the tree.

So, if the input is like then the output will be 5

To solve this, we will follow these steps:

• ans := 0

• Define a function getMaxPath() . This will take node

• if node is null, then

• return 0

• leftCnt := getMaxPath(left of node)

• rightCnt := getMaxPath(right of node)

• temp := 1 + maximum of leftCnt and rightCnt

• ans := maximum of ans and l+r+1

• From the main method do the following −

• getMaxPath(root)

• return ans

Let us see the following implementation to get better understanding −

## Example

Live Demo

class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right

class Solution:
def solve(self, root):
self.ans = 0
def getMaxPath(root):
if root is None:
return 0
l = getMaxPath(root.left)
r = getMaxPath(root.right)
temp = max(l, r) + 1
self.ans = max(self.ans, l + r + 1)
return temp
getMaxPath(root)
return self.ans
ob = Solution()
root = TreeNode(2)
root.left = TreeNode(10)
root.right = TreeNode(4)
root.right.left = TreeNode(8)
root.right.right = TreeNode(2)
root.right.left.left = TreeNode(6)
print(ob.solve(root))

## Input

root = TreeNode(2)
root.left = TreeNode(10)
root.right = TreeNode(4)
root.right.left = TreeNode(8)
root.right.right = TreeNode(2)
root.right.left.left = TreeNode(6)

## Output

5