TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) 
 {
     if(root==NULL)
         return NULL;
     if(p==NULL)
         return q;
     if(q==NULL)
         return p;
     list<TreeNode*> pp,qq;
     build_list(root,p,pp);
     pp.push_front(root);
     build_list(root,q,qq);
     qq.push_front(root);
     return find_common_node(pp,qq);
 }
Esempio n. 2
0
int main(void) {
    
    int input_data[] = {1,2,3,4,5,6};
    int i = 0; 
    link_list *head = NULL;
    head = (link_list*)malloc(sizeof(link_list));
    if (head == NULL) {
        fprintf(stderr, "init link list failed.\n");
        return -1;
    }
    head->next = NULL;

    for (; i < 6; ++i) {
        if (insert_link_list(head, input_data[i]) != 0) {
            fprintf(stderr, "insert data failed.\n");
            return -1;
        }
    }

    link_list *head2 = NULL; 
    head2 = (link_list*)malloc(sizeof(link_list));
    if (head2 == NULL) {
        fprintf(stderr, "init link list failed.\n");
        return -1;
    } head2->next = NULL;

    for (i = 7; i <= 10; ++i) {
        if (insert_link_list(head2, i) != 0) {
            fprintf(stderr, "insert data failed.\n");
            return -1;
        }
    }

    link_list *tail2 = head2; 

    while (tail2->next != NULL) {
        tail2 = tail2->next;
    }

    tail2->next = head->next->next;

    tail2 = find_common_node(head, head2);
    if (tail2 == NULL) {
        fprintf(stderr, "can't find common node or find failed.\n");
        return -1;
    }
    else {
        printf("%d\n", tail2->data);
    }

    while (head != tail2) {
        link_list *tmp = head;
        head = head->next;
        free(tmp);
    }

    while (head2 != tail2) {
        link_list *tmp = head2;
        head2 = head2->next;
        free(tmp);
    }

    while (tail2 != NULL) {
        link_list *tmp = tail2; 
        tail2 = tail2->next; 
        free(tmp);
    }

    return 0;
}