Find recent public ancestor

Source: Internet
Author: User
Find recent public ancestor

The premise of finding is that node A and Node B are all in the tree.

The main action object is a two-fork search tree, the following steps: Remember the current root node is x, if a < X and B > x (or vice versa), then X is the required ancestor; If a, B is less than (greater than) x, the description also continues to look to the left (right) subtree, if x = a (b) b) is the ancestor of B (a).

/* Find common ancestor *
/int findAncestor (node* root, int a, int b)
{
    //b node at the left and right side of the root node, indicating that the root node is the common ancestor
    if (a < ROOT-&G T;data && B > Root->data | | A > Root->data && B < root->data)
        return root->data;

    A (b) is the ancestor of B (a)
    if (Root->data = = A | | root->data = = b)
        return root->data;

    Continue to the left and right subtree to find
    if (a < Root->data && B < root->data)
        return FindRoot (Root->lchild, A, b); C12/>else if (a > root->data && B > Root->data)
        return FindRoot (Root->rchild, A, b);
}

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.