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 | 4009 |
2 | jiangly | 3823 |
3 | Benq | 3738 |
4 | Radewoosh | 3633 |
5 | jqdai0815 | 3620 |
6 | orzdevinwang | 3529 |
7 | ecnerwala | 3446 |
8 | Um_nik | 3396 |
9 | ksun48 | 3390 |
10 | gamegame | 3386 |
# | User | Contrib. |
---|---|---|
1 | cry | 165 |
2 | maomao90 | 164 |
3 | Um_nik | 163 |
4 | atcoder_official | 160 |
4 | adamant | 160 |
6 | -is-this-fft- | 158 |
7 | awoo | 157 |
8 | TheScrasse | 154 |
8 | Dominater069 | 154 |
8 | nor | 154 |
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).