Before introducing the official solution, let me say something about my method:
Node {struct int Data; int parent, left, right; // static implementation };
- When the establishment of the tree, through mass participation, to achieve the establishment of parent (pointing to the parent node)
- Our aim is to find i, j of the common node; if parent = -1, then that is the root node.
- Found i, j corresponding to the node, and depending on the value of the parent to the root node i, j is stored in the path of the stack. At this time, two stacks obtained.
- Compare the first element of the stack, the last element is the same LCA.
The advantage of this approach is that: Nothing too many restrictions, efficiency is also OK.
If the binary tree stored according to the order, (general index is assigned number), then the algorithm can solve it:
- To find i, j of LCA
- If i <j, i is lower than described or layer j, i or j in the left; therefore j = j / 2;
- If i> j, empathy, i = i / 2;
- Until i = j, is stopped, then it represents the i / j is the LCA.