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 | 3885 |
3 | jqdai0815 | 3682 |
4 | Benq | 3580 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3506 |
7 | ecnerwala | 3505 |
8 | Radewoosh | 3457 |
9 | Kevin114514 | 3377 |
10 | gamegame | 3374 |
# | User | Contrib. |
---|---|---|
1 | cry | 170 |
2 | Um_nik | 162 |
3 | atcoder_official | 161 |
4 | maomao90 | 158 |
4 | -is-this-fft- | 158 |
6 | djm03178 | 157 |
7 | Dominater069 | 156 |
8 | adamant | 154 |
9 | luogu_official | 153 |
10 | awoo | 152 |
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).