- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
- Related Articles
- Program to find the largest sum of the path between two nodes in a binary tree in Python
- Program to find longest even value path of a binary tree in Python
- Program to find length of longest alternating path of a binary tree in python
- Program to find length of longest consecutive path of a binary tree in python
- C++ Program to Find Path Between Two Nodes in a Graph
- Program to find out distance between two nodes in a binary tree in Python
- Program to find length of the longest path in a DAG without repeated nodes in Python
- Find distance between two nodes of a Binary Tree in C++ Program
- Program to find length of the longest path in an n-ary tree in Python
- XOR of the path between any two nodes in a Binary Tree in C++
- Program to find sum of longest sum path from root to leaf of a binary tree in Python
- Print path between any two nodes in a Binary Tree in C++ Programming.
- Find distance between two nodes of a Binary Tree in C++
- Program to find length of longest matrix path length in Python
- Python Program to Find the Sum of all Nodes in a Tree

Advertisements