
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 Articles
- 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 minimums of each sublist from a list in Python
- Program to find minimum possible sum by changing 0s to 1s k times from a list of numbers in Python?
- Python program to find sum of elements in list
- Program to find minimum digits sum of deleted digits in Python
- Python Program for Find minimum sum of factors of number
- Python program to find Cumulative sum of a list
- Find sum of elements in list in Python program
- Program to find maximum sum of popped k elements from a list of stacks in Python
- Program to find minimum absolute sum difference in Python
- Program to find minimum number of deletions required from two ends to make list balanced in Python
- Program to find sum of the right leaves of a binary tree in C++
- Program to find equal sum arrays with minimum number of operations in Python

Advertisements