I Came across a question I couldn't figure out.
Assume A binary tree, where each node has a pointer to its parent, and two children. We receive input for r, p,q ( root, and two nodes from the tree) and we want to find the depth difference between p and q, Without Traversing all the way up to the root.
Limitations and Assumptions:
- No memory usage (meaning no arrays, variables are ok)
- Assume the nodes Lowest Common Ancestor isn't the root (and for simplicity let's assume the LCA is far from the root in Big-O notation Terms.
Just to clarify - Basically, the question is how do we figure out the depth difference without going all the way up to the root, and without memory.
Thanks!
It isn't saying that you cannot traverse all the way up to the root. It just says that the final outcome may not be the root.
First, define a function to determine the depth of a node (pseudo code):
Simply call this function for both nodes, and take the difference.
As an additional feature, you can use this information to find the Lowest Common Ancestor:
Use the depth difference to walk up from the deepest node of the two up until you are at the same depth as the other. From then on walk upwards from both nodes in tandem, until you arrive at the same node from both sides: