1151 LCA in a Binary Tree (30 point(s))

Ideas:

Recursively, given a tree, confirm whether the root node is the lowest common ancestor of u and v, if not, then search for the left subtree or the right subtree.

If both u and v exist in the tree, then search for LCA, if not, print the corresponding error message.

First-order traversal, if the root node of the current tree is u or v, or the position of the root node in the middle-order traversal sequence is between u and v, then LCA is the root node;

If it is not, then the position of the root node in the mid-order traversal sequence is greater than u and v, then the LCA of u and v is searched in the left subtree, otherwise, it is searched in the right subtree.

1151 LCA in a Binary Tree (30 point(s))

The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U and V as descendants.

Given any two nodes in a binary tree, you are supposed to find their LCA.

Example:

#include<iostream>
#include<vector>
#include<unordered_map>
using namespace std;

vector<int> inorder, preorder;
unordered_map<int, int> order;

int _LCA(int ib, int ie, int pb, int pe, int uin, int vin)
{
    int root = order[preorder[pb]];
    if(uin == root || vin == root) return inorder[root];
    else if(uin > vin) {
        if(vin < root && root < uin) return inorder[root];
        else if(uin < root) return _LCA(ib, root, pb+1, pb+1+root-ib, uin, vin);
        else return _LCA(root, ie, pb+1+root-ib, pe, uin, vin);
    } else {
        if(uin < root && root < vin) return inorder[root];
        else if(vin < root) return _LCA(ib, root, pb+1, pb+1+root-ib, uin, vin);
        else return _LCA(root, ie, pb+1+root-ib, pe, uin, vin);
    }
}

int LCA(int u, int v)
{
    return _LCA(0, inorder.size(), 0, preorder.size(), order[u], order[v]);
}

int main()
{
    int M, N;
    cin >> M >> N;
    inorder.resize(N+1), preorder.resize(N+1);
    for(int i = 0; i < N; i++) cin >> inorder[i], order[inorder[i]]=i;
    for(int i = 0; i < N; i++) cin >> preorder[i];
    for(int i = 0; i < M; i++) {
        int u, v;
        cin >> u >> v;
        if(order.count(u) == 0 && order.count(v) == 0) 
            printf("ERROR: %d and %d are not found.\n", u, v);
        else if(order.count(u) == 0 || order.count(v) == 0) 
            printf("ERROR: %d is not found.\n", order.count(u) == 0 ? u : v);
        else {
            int lca = LCA(u, v);
            if(lca == u || lca == v) printf("%d is an ancestor of %d.\n", lca, lca == u ? v : u);
            else printf("LCA of %d and %d is %d.\n", u, v, lca);
        }
    }
}

 

Guess you like

Origin blog.csdn.net/u012571715/article/details/114630920