求解思路:

采用递归,深度优先遍历,找到一个节点时,返回,逐层记录遍历方向,另一个节点
同,这样深度优先遍历后,可以找到这两个节点由根节点访问的路径,然后沿着这个
路径找到分叉的地方就行了

代码:

 
  
  1. #include <stdlib.h>  
  2. #include <stdio.h>  
  3.  
  4. typedef struct TNode  
  5. {  
  6.     int data;  
  7.     int pathA;  
  8.     int pathB;  
  9.     TNode* lchild;  
  10.     TNode* rchild;  
  11. }TNode,*BTree;  
  12.  
  13. //采用递归进行深度优先遍历  
  14. //计算出路径  
  15. int traverse(BTree t,int x,int flag)  
  16. {  
  17.     if (t == NULL) return 0;  
  18.     if (t->data == x) return 1;  
  19.     if (traverse(t->lchild,x,flag)==1)  
  20.     {  
  21.         if (flag == 1) t->pathA = 1;  
  22.         else t->pathB = 1;  
  23.         return 1;  
  24.     }  
  25.     if (traverse(t->rchild,x,flag)==1)  
  26.     {  
  27.         if (flag == 1) t->pathA = 2;  
  28.         else t->pathB = 2;  
  29.         return 1;  
  30.     }     
  31. }  
  32.  
  33. int main()  
  34. {  
  35.     BTree tree = (BTree)malloc(sizeof(TNode));  
  36.     tree->data = 1;  
  37.     tree->pathA = 0;  
  38.     tree->pathB = 0;  
  39.     tree->lchild = (TNode*)malloc(sizeof(TNode));  
  40.     tree->lchild->data = 2;  
  41.     tree->lchild->pathA = 0;  
  42.     tree->lchild->pathB = 0;  
  43.     tree->rchild = (TNode*)malloc(sizeof(TNode));  
  44.     tree->rchild->data = 3;  
  45.     tree->rchild->pathA = 0;  
  46.     tree->rchild->pathB = 0;  
  47.     tree->rchild->lchild = NULL;  
  48.     tree->rchild->rchild = NULL;  
  49.     tree->lchild->lchild = (TNode*)malloc(sizeof(TNode));  
  50.     tree->lchild->lchild->data = 4;  
  51.     tree->lchild->lchild->pathA = 0;  
  52.     tree->lchild->lchild->pathB = 0;  
  53.     tree->lchild->lchild->lchild = NULL;  
  54.     tree->lchild->lchild->rchild = NULL;  
  55.     tree->lchild->rchild = (TNode*)malloc(sizeof(TNode));  
  56.     tree->lchild->rchild->data = 5;  
  57.     tree->lchild->rchild->pathA = 0;  
  58.     tree->lchild->rchild->pathB = 0;  
  59.     tree->lchild->rchild->lchild = NULL;  
  60.     tree->lchild->rchild->rchild = NULL;  
  61.       
  62.     int a,b;  
  63.     printf("please input a,b:");  
  64.     scanf("%d %d",&a,&b);     
  65.     if (traverse(tree,a,1)!=1) printf("no a");  
  66.     if (traverse(tree,b,2)!=1) printf("no b");  
  67.       
  68.     //从根节点开始向下遍历,找到路径分叉点  
  69.     TNode* node = tree;  
  70.     while(node&&(node->pathA==node->pathB))  
  71.     {  
  72.         if (node->pathA == 1) node = node->lchild;  
  73.         else node = node->rchild;  
  74.     }     
  75.     printf("the common father node is:%d",node->data);  
  76.     return 0;  

 

示例:

please input a,b:4 3
the common father node is:1