
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Sum of Longest Sum Path from Root to Leaf in Python
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 −
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): 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))
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
20
Advertisements