- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have a binary tree, we have to find the sum of the longest path from the root to a leaf node. If there are two same long paths, return the path with larger sum.

So, if the input is like

then the output will be 20.

To solve this, we will follow these steps −

Define a function rec() . This will take curr

if curr is null, then

return(0, 0)

bigger := maximum of rec(left of curr) , rec(right of curr)

return a pair (bigger[0] + 1, bigger[1] + value of curr)

From the main method do the following −

ret := rec(root)

return the 1th index of ret

Let us see the following implementation to get better understanding −

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): def rec(curr): if not curr: return (0, 0) bigger = max(rec(curr.left), rec(curr.right)) return (bigger[0] + 1, bigger[1] + curr.val) return rec(root)[1] 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))

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)

20

- Related Questions & Answers
- Program to find largest sum of any path of a binary tree in Python
- Program to print the longest leaf to leaf path in a Binary tree using C++
- 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
- Program to find longest even value path of a binary tree in Python
- Program to find sum of all numbers formed by path of a binary tree in python
- Sum Root to Leaf Numbers in Python
- Program to find sum each of the diagonal path elements in a binary tree in Python
- Program to find length of longest path with even sum in Python
- Program to find leaf and non-leaf nodes of a binary tree in Python
- Binary Tree Maximum Path Sum in Python
- Find the sum of left leaf nodes of a given Binary Tree in C++
- Program to print the first shortest root to leaf path in a Binary Tree using C++
- Program to find most frequent subtree sum of a binary tree in Python
- Python Program to Find the Sum of All Nodes in a Binary Tree

Advertisements