Recent common ancestor Lowest Common Ancestors

Before introducing the official solution, let me say something about my method:

Node {struct 
    int Data; 
    int parent, left, right; // static implementation 
};
  1. When the establishment of the tree, through mass participation, to achieve the establishment of parent (pointing to the parent node)
  2. Our aim is to find i, j of the common node; if parent = -1, then that is the root node.
  3. 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.
  4. 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:

  1. To find i, j of LCA
  2. If i <j, i is lower than described or layer j, i or j in the left; therefore j = j / 2;
  3. If i> j, empathy, i = i / 2;
  4. Until i = j, is stopped, then it represents the i / j is the LCA.

 


 

Guess you like

Origin www.cnblogs.com/yy-1046741080/p/11505547.html