- 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

# Program to find sum of minimum trees from the list of leaves in python

Suppose we have a list of numbers called nums. This list is representing the leaf nodes in inorder traversal of a tree. Here the internal nodes have have 2 children and their value is same as the product of the largest leaf value of its left subtree and the largest leaf value of its right subtree. We have to find the sum of the tree with the minimum sum of its values

So, if the input is like nums = [3, 5, 10], then the output will be 83.

To solve this, we will follow these steps:

- res := sum of all elements in nums
- while size of nums > 1, do
- i := index of minimum element of nums
- left := nums[i - 1] when i > 0 otherwise infinity
- right := nums[i + 1] when i < size of nums - 1 otherwise infinity
- res := res + (minimum of left and right) * ith element of nums, then delete ith element from nums

- return res

Let us see the following implementation to get better understanding:

## Example Code

class Solution: def solve(self, nums): res = sum(nums) while len(nums) > 1: i = nums.index(min(nums)) left = nums[i - 1] if i > 0 else float("inf") right = nums[i + 1] if i < len(nums) - 1 else float("inf") res += min(left, right) * nums.pop(i) return res ob = Solution() nums = [3, 5, 10] print(ob.solve(nums))

## Input

[3, 5, 10]

## Output

83

- Related Questions & Answers
- Program to find out the minimum value from sum of node values of sub-trees in Python
- Minimum sum path between two leaves of a binary trees in C++
- Program to find sum of odd elements from list in Python
- Program to find sum of the right leaves of a binary tree in C++
- Program to find sum of the minimums of each sublist from a list in Python
- Python program to find sum of elements in list
- Python Program for Find minimum sum of factors of number
- Program to find minimum digits sum of deleted digits in Python
- Python program to find Cumulative sum of a list
- Find sum of elements in list in Python program
- Program to find minimum possible sum by changing 0s to 1s k times from a list of numbers in Python?
- C Program to Find the minimum sum of factors of a number?
- Program to find maximum sum of popped k elements from a list of stacks in Python
- Java Program to find minimum sum of factors of a number
- Python Program to find the sum of array

Advertisements