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

思路:

递归,给定一棵树,确认根节点是否u和v的最低公共祖先,如果不是,那么对左子树或者右子树查找。

如果u和v都存在树中,那么查找LCA,如果不是,打印对应错误信息。

先序遍历,如果当前树的根节点是u或者v,或者中序遍历序列中,根节点的位置在u和v之间,那么LCA就是根节点;

如果不是,那么中序遍历序列中,根节点的位置大于u和v,那么在左子树查找u和v的LCA,否则在右子树查找。

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);
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值