This problem can be considered in three situations:
Case 1: Unknown root, but each node has a parent pointer
At this time, we can start from two nodes and move along the parent pointer to the root node to get two linked lists and then find the first public node of the two linked lists. This method is very simple and does not need to be explained in detail.
Case 2: The node has only the left and right pointers, and there is no parent pointer. The root is known.
Idea: There are two situations: one is that the two nodes (a and B) to be searched are on both sides of the node (Root) to be traversed, this node is the closest public parent node of the two nodes;
Second, if two nodes are on the same side, root-> left or root-> right is null, And A or B is returned on the other side. The other side returns their minimum public parent node.
Recursion has two egresses. If A or B is not found, null is returned. If A or B is met, A is returned immediately.
// Description of the Binary Tree node typedef struct bitnode {char data; struct bitnode * lchild, * rchild; // left and right children} binarytreenode; // The node has only the left and right pointers, no parent pointer. Root knows binarytreenode * findlowestcommonancestor (binarytreenode * root, binarytreenode * a, binarytreenode * B) {If (root = NULL) return NULL; if (root = A | root = B) Return root; binarytreenode * Left = findlowestcommonancestor (root-> lchild, a, B); binarytreenode * Right = Findlowestcommonancestor (root-> rchild, a, B); If (left & right) return root; return left? Left: Right ;}
Case 3: A binary tree is a binary search tree, and the values of root and two nodes (A, B) are known.
// Binary Tree is a binary search tree. The root and the values of the two nodes (A, B) are known as binarytreenode * findlowestcommonancestor (binarytreenode * root, binarytreenode * a, binarytreenode * B) {char min, Max; if (a-> data <B-> data) min = A-> data, max = B-> data; elsemin = B-> data, max = A-> data; while (Root) {If (root-> DATA> = min & root-> data <= max) return root; else if (root-> data <min & root-> data <max) root = root-> rchild; elseroot = root-> lchild;} return NULL ;}