I haven't used Binary Trees for a long time. Recently I have used binary trees and found that a lot of knowledge needs to be consolidated. An algorithm involved in the middle is to find the nearest ancestor of any two nodes. Through my review and calculation, I finally proposed the following method. There are also many other ways to achieve it on the Internet. Once again, I only recorded and accumulated my work for several hours! The program is written in C language. I personally think it is more convenient to use C. First, data structure definition: [cpp] typedef char TElemType; typedef bool Status; typedef struct BiTNode {TElemType data; struct BiTNode * lchild, * rchild;} BiTNode, * BiTree; the second is building, which is defined by the tree and established in the first sequential recursion mode. [Cpp] BiTNode * CreateBiTree () {char ch; BiTNode * T; scanf ("% c", & ch); if (ch = '#') T = 0; else {T = (BiTree) malloc (sizeof (BiTNode); T-> data = ch; T-> lchild = CreateBiTree (); t-> rchild = CreateBiTree ();} return T;} The separator of an empty node is "#" in this field, which can be replaced by other characters. The basic algorithm used to search for recent ancestors is recursion. Each node is first determined whether there is a direct association. If none of the algorithms are found, their immediate parent nodes are obtained, the depth of the two nodes is used to determine which parent node is used for the next call. The specific implementation is as follows: [cpp] // find the nearest common ancestor node of two nodes. BiTNode * FindNearestAncestor (BiTNode * root, BiTNode * p1, BiTNode * p2, int h1, int h2) {if (! P1 |! P2) return 0; if (p1 = p2) {if (p1 = root) return root; return p1 ;} if (p1 = p2-> lchild | p1 = p2-> rchild) return p2; if (p2 = p1-> lchild | p2 = p1-> rchild) return p1; if (h1 = h2) return FindNearestAncestor (root, GetParent (root, p1), GetParent (root, p2), h1-1, h2-1); else return FindNearestAncestor (root, h1> h2? GetParent (root, p1): p1, h1