Find the maximum difference between any combination of child and parent node in a given binary tree. Here child node can be any level below parent node, but should be in the same sub tree starting from parent node
# | User | Rating |
---|---|---|
1 | tourist | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 161 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | Dominater069 | 154 |
8 | awoo | 154 |
10 | luogu_official | 150 |
Find the maximum difference between any combination of child and parent node in a given binary tree. Here child node can be any level below parent node, but should be in the same sub tree starting from parent node
Name |
---|
Since your question is not very clear, I am assuming the following things: 1. The difference of nodes which you are talking about is the difference between given node's value and not their distance. 2. The input is a node and we have to figure out the maximum difference between the value of input node and any of the nodes in its subtree with input node as the root.
Solution: Use DFS and Segment Tree. First of all run a DFS to make preorder traversal array and at the same time calculate size of the subtree for every node. Then build a segment tree out of this preorder traversal array and query to find range maximum between starting parent node location and its size of subtree.
P.S : Do add the question link, if any!
Yes its between the value of the nodes.Can you please explain your approach little more.And your second assumption is wrong we need to find the maximum difference for any pair of child and parent.I hope now you understand the question more clearly.
If i correctly understood the problem, if there are two edges 1->2, 2->3, node 1 have value 10, 2 — 30, 3 — 40, answer is 30. Solution: for each v store minimum of its subtree and maximum (it can be done during dfs). Then try to increase ans using abs(a[v] — mn[v]) and abs(a[v] — mx[v]). Complexity is O(n).