Given a binary tree: Binary tree of height 3
I want to find the horizontal distance between two nodes at the same level also counting the nodes that are not there in between while not counting the nodes themselves, Say in
f
/ \
g h
/ \ / \
a d
in between the nodes a and d there is a horizontal distance of 2.
Edit:
Please see distance between a to d is calculated on the same level not including the parent or child nodes of either a or d but only the missing nodes at the same level. so distance between a to d would be a>(x>y)>d where in x and y are the missing child nodes of node g and h respectively. Hence not counting the target nodes a and d there'll be a horizontal distance of 2
For the nodes of a binary tree, the horizontal distance is defined as follows: Horizontal distance of the root = 0. Horizontal distance of a left child = horizontal distance of its parent - 1. Horizontal distance of a right child = horizontal distance of its parent + 1.
Horizontal Distance (HD): is the distance of a node from the root node. The HD of the root node is zero. Any node that falls in the vertical line after the root node line will be positive, and any node that falls in the vertical line to the left of the root node will be negative.
Steps of algorithm We will use Dijkstra's Algorithm to store the shortest distance of each node from B, and we will store that distance in the array named distB[]. Edge[i] = {u[i], v[i], wt[i]}, here u[i] and v[i] are the nodes which are connected by this edge and wt[i] is the weight of this edge.
The distance between two adjacent nodes ortwo adjacent antinodes is equal to half of the wavelength.
Think of it this way:
a
/ \
b c
/ \ / \
e f g h
Now, you want to determine horizontal distance between nodes at the same level. Eg: f and g. Here is a step by step approach:
f
(starting node), set counter to 0.g
(end node) is encountered, then stop traversing.Update:
As pointed out by anand_v.singh, if the tree might not be completely filled at all levels, then it can produce wrong results.
To overcome this problem, an additional parameter called tree_height
will be determined. Suppose, the height of the tree was 3, then the array will contain at most 2tree_height -1 elements, all initialized to a value that is not equal to the value of any tree nodes.
Now, you can use something like array representation of binary heap, to place node values into the array, at their respective indices. Then follow the above-mentioned procedure to obtain the results.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With