871. Tree Greatness
Given a binary tree consisting exactly of n vertices and rooted at vertex 1. Each vertex V of this tree has a value value[v] assigned to it.
The greatness of a vertex i = (value[i] x 1) + (value[par[i]] x 2) + (value[par[par[i]] x 3) + (value[par[par[par[i]]] x 4) + ... until you reach the root i.e par[par[.....par[i]...]] is the rootÂ
where par[i] represents the parent of vertex i.
Given a value array where value[i] (1-based indexing) corresponds to the value assigned to the ith vertex. The greatness of an entire tree is defined as the maximum of greatness of any of its vertices. Find the maximum greatness of the tree.Â
e.g. Consider the above tree where the number inside the node represents the value of the node.
The greatness of vertex with value 4 will be :Â (value x 1) + (par[4] x 2) + (par[par[4]] x 3).
The greatness of vertex with value 4 will be : (4 x 1) + (2 x 2) + (1 x 3) => 11.
Similarly greatness of vertex 6 will be : (6 x 1) + (3 x 2) + (2 x 3) + (1 x 4) => 22.
Example 1:
Input : value = [2, 3, -2, -1, -7, 5], root = 1 2 6 3 4 null null null null 5
Output : 23
Example 2:
Input : value = [1, 2, 3, 4, 5], root = 1 2 3 4 null 5
Output : 14
Explanation : Greatness for vertex 1 => 1*1 => 1.
Greatness for vertex 2 => 2*1 + 1*2 => 4.
Greatness for vertex 3 => 3*1 + 1*2 => 5.
Greatness for vertex 4 => 4*1 + 2*2 + 1*3 => 11.
Greatness for vertex 5 => 5*1 + 3*2 + 1*3 => 14.
So the maximum greatness of a tree is obtained from vertex 5. I.e 14.
Now Your Turn!
Pick the correct output for the given inputInput : value = [1, 2, 3, 4, 5], root = 1 2 3 4 null 5
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= n <= 105
- -105 <= value[i] <= 105