Lowest Common Ancestor of a Binary Search Tree

来源:互联网 发布:网络爬虫 登陆 编辑:程序博客网 时间:2024/05/29 06:42
情况一:节点只有左、右指针,root已知

思路:一开始想到用递归去做,但是因为本来对递归的概念还很模糊,所以在设计递归出口的时候一点思路也没有,翻了关于递归的资料,找到一张图能很好地解释递归:

递归有两个出口,一是没有找到a或者b,则返回NULL;二是只要碰到a或者b,就立刻返回,这样的话下面的代码就很好理解了。
[cpp] view plain copy
  1. // 二叉树结点的描述    
  2. typedef struct BiTNode    
  3. {    
  4.     char data;    
  5.     struct BiTNode *lchild, *rchild;      // 左右孩子    
  6. }BinaryTreeNode;   
  7.   
  8. // 节点只有左指针、右指针,没有parent指针,root已知  
  9. BinaryTreeNode* findLowestCommonAncestor(BinaryTreeNode* root , BinaryTreeNode* a , BinaryTreeNode* b)  
  10. {  
  11.     if(root == NULL)  
  12.         return NULL;  
  13.     if(root == a || root == b)  
  14.         return root;  
  15.     BinaryTreeNode* left = findLowestCommonAncestor(root->lchild , a , b);  
  16.     BinaryTreeNode* right = findLowestCommonAncestor(root->rchild , a , b);  
  17.     if(left && right)  
  18.         return root;  
  19.     return left ? left : right;  
  20. }  

情况二: 二叉树是个二叉查找树,且root和两个节点的值(a, b)已知
[cpp] view plain copy
  1. // 二叉树是个二叉查找树,且root和两个节点的值(a, b)已知  
  2. BinaryTreeNode* findLowestCommonAncestor(BinaryTreeNode* root , BinaryTreeNode* a , BinaryTreeNode* b)  
  3. {  
  4.     char min  , max;  
  5.     if(a->data < b->data)  
  6.         min = a->data , max = b->data;  
  7.     else  
  8.         min = b->data , max = a->data;  
  9.     while(root)  
  10.     {  
  11.         if(root->data >= min && root->data <= max)  
  12.             return root;  
  13.         else if(root->data < min && root->data < max)  
  14.             root = root->rchild;  
  15.         else  
  16.             root = root->lchild;  
  17.     }  
  18.     return NULL;  
  19. }  
0 0
原创粉丝点击