Find the nearest common ancestor of two nodes in a tree

Source: Internet
Author: User
Tags bool printf

The sword refers to the last question on offer, and a recursive function has been tuned for an afternoon to get the correct result.

Topic Description:

Given a tree, it also gives two nodes in the tree, and asks for their lowest common ancestor.

Input:

The input may contain more than one test sample.

For each test case, the first behavior of the input is a number n (0<n<1000), which represents the number of test examples.

Each test sample includes two rows, the first behavior a first sequence traversal sequence of a binary tree, in which the left and right subtree is empty, is replaced with 0, among which the number of nodes of the two-node_num<10000 tree is the same.

The values of the two nodes in the second behavior tree are M1 and M2 (0<m1,m2<10000).

Output:

corresponding to each test case,

Outputs the value of the lowest common ancestor node of two nodes in a given tree, and outputs "my God" if two given nodes have no minimum common ancestor.

Sample input:

2

1 2 4 6 0 0 7 0 0 5 8 0 0 9 0 0 3 0 0

6 8

1 2 4 6 0 0 7 0 0 5 8 0 0 9 0 0 3 0 0

6 12

Sample output:

2

My God

This kind of topic, the method is quite many, the idea is not difficult to understand, the basic is all sorts of traversal of variant, mainly writes the code, especially is based on the recursion code.

First of all, if the two-fork sort tree naturally goes without saying, the judgment is whether the value of the node is located between the two nodes that are entered, and can be done in a forward-order traversal.

If it is a common tree or binary tree, the idea of solving the problem is the same, you can consider the first sequence traversal, get two paths, with a linked list or array to save, and then find two paths of the last public node can be. can also be followed by the way of traversal, traversing to the input node, the node and its subsequent traversal to the node are saved to a linked list or array, and then find two paths of the first public machine node can be.

The following is a sequence traversal and the code to save the path with an array.

#include <stdio.h> #include <stdlib.h> #include <stdbool.h> typedef struct BTNODE {St  
    Ruct Btnode *lchild;  
    struct Btnode *rchild;  
int data;  
     
}btnode,*btree;
/* Pre-order traversal locate the node path to the root node to the data field, and save it in the path array, return to the column page: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/ Here index is the subscript of the element that is saved to the path array, *len is used to save the path length, and if the Val is found, return the ture and return false/bool Getpretraversepath (Btree Ptree,int Val,  
        int *path,int Index,int *len) {if (PTree = = NULL) {*len = 0;  
    return false;  
    } Path[index] = ptree->data;  
        if (Ptree->data = = val) {*len = index+1;  
    return true;  
        else {bool can;  
        can = Getpretraversepath (Ptree->lchild,val,path,index+1,len);  
        if (!can) can = Getpretraversepath (Ptree->rchild,val,path,index+1,len);  
    return can; }/* Gets the last public node of two paths, because some of the preceding nodes are the same in the result of the first order traversal of the tree, so it mustCan find the last same node */int Getfirstcommonnode (int *path1,int len1,int *path2,int len2) {int shortlen = Len1<len2? Le  
    N1:len2;  
    int i;  
    for (i=0;i<shortlen;i++) {if (Path1[i]!= path2[i]) break;  
return path1[i-1];  
    }/* Creates a two-fork tree based on the first-order traversal sequence, which may change the point of the root node, so the two-level pointer to the incoming Btnode/void Createbtree (Btree *proot) {int data;  
    scanf ("%d", &data);  
    if (data = = 0) *proot = NULL;  
        else {*proot = (btree) malloc (sizeof (Btnode));   
        if (*proot = NULL) exit (exit_failure);  
        (*proot)->data = data;  
        (*proot)->lchild = NULL;  
        (*proot)->rchild = NULL;  
        Createbtree (& ((*proot)->lchild));  
    Createbtree (& ((*proot)->rchild)); }/* Destroy the binary tree/void Destroybtree (Btree proot) {if (proot!= NULL) {if (Proot->lchi  
     LD!= NULL) destroybtree (proot->lchild);   if (proot->rchild!= NULL) destroybtree (proot->rchild);  
        Free (proot);  
    Proot = NULL;  
    int main () {int path1[10000];  
     
    int path2[10000];  
    int n;  
        while (scanf ("%d", &n)!= EOF) {int i;  
            for (i=0;i<n;i++) {btree proot = NULL;  
     
            Createbtree (&proot);  
            int val1,val2;  
     
            scanf ("%d%d", &val1,&val2);  
            int len1,len2;  
            BOOL Can1 = Getpretraversepath (PROOT,VAL1,PATH1,0,&AMP;LEN1);  
     
            BOOL can2 = Getpretraversepath (PROOT,VAL2,PATH2,0,&AMP;LEN2);  
            if (can1 && can2) printf ("%d\n", Getfirstcommonnode (Path1,len1,path2,len2));  
     
            else printf ("My god\n");  
        Destroybtree (Proot);  
} return 0; }

/**************************************************************

problem:1509

User:mmc_maodun

Language:c

result:accepted

time:130 ms

memory:920 kb

****************************************************************/

PS: Find the recursive code for the path for one afternoon, finally done, every encounter about the tree problem, is generally three kinds of way to achieve a variety of traversal, naturally think of recursion, some write is very easy, some write is always very tangled, especially to return the bool variable, or too much food, Back to take a time to the two-fork tree recursive implementation of some of the topics well summarized.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.