PAT甲级-1151 LCA in a Binary Tree (30 分)

题目:1151 LCA in a Binary Tree (30 分)
分析:一般二叉树的LCA,先根据中序和前序建立二叉树,然后进行查找,根据高度来判断:
  1. 把高度低的其中一个节点向上移动到与另外一个高度相同为止
  2. 若移动到该节点时,刚好为另外一个节点,那么这个节点就是另外一个节点的ancestor
  3. 否则两个节点继续同时向上,直到找到相同的父母为止
#include <iostream>
#include<cstring>
#include<vector>
#include<stdio.h>
#include<queue>
#include<math.h>
#include<stack>
#include<algorithm>
#include<map>
#include<set>
#include<iostream>
using namespace std;
#define MAX 100001
#define MM  1020
typedef long long ll;
int n,m,k;
int in[10001];
int pre[10001];
struct Node{
    int key;
    Node *left;
    Node* right;
    Node *last;
    int height;
};
Node *create(int prel,int prer,int inl,int inr,int h)
{
    if(prel>prer)
        return NULL;
    Node *root = (Node*)malloc(sizeof(Node));
    int key = pre[prel];
    root->key = key;
    root->height = h;
    int idx = 0;
    for(int i = 0;i<=inr;i++)
    {
        if(in[i] == key)
        {
            idx = i;
            break;
        }
    }
    int num = idx - inl;
    root->left = create(prel+1, prel+num, inl,idx-1,h+1);
    if(root->left!=NULL)
        root->left->last = root;
    root->right = create(prel+num+1,prer, idx+1,inr,h+1);
    if(root->right!=NULL)
        root->right->last = root;
    return root;
}
Node* get(Node*root,int x)
{
    if(root==NULL)
        return NULL;
    if(x == root->key)
        return root;
    Node *a = get(root->left,x);
    if(a!=NULL)
        return a;
    a = get(root->right,x);
    if(a!=NULL)
        return a;
}
void mov(Node *root,int a,int b)
{
    Node*x = get(root,a);
    Node*y = get(root,b);
    if(x == NULL && y == NULL)
        printf("ERROR: %d and %d are not found.\n",a,b);
    else if(x == NULL)
        printf("ERROR: %d is not found.\n",a);
    else if(y == NULL)
        printf("ERROR: %d is not found.\n",b);
    else{
        while(x->height != y->height)
        {
            if(x->height>y->height)
                x = x->last;
            else
                y = y->last;
        }
        if(x == y)
        {
            if(x->key == a)
                printf("%d is an ancestor of %d.\n",a,b);
            else
                printf("%d is an ancestor of %d.\n",b,a);
        }
        else{
            while(x!=y)
            {
                x = x->last;
                y = y->last;
            }
            printf("LCA of %d and %d is %d.\n",a,b,x->key);
        }
    }
}
int main()
{
    cin>>m>>n;
    for(int i = 0;i<n;i++)
        cin>>in[i];
    for(int i = 0;i<n;i++)
        cin>>pre[i];
    Node *root=NULL;
    root=create(0,n-1,0,n-1,0);
    while(m--)
    {
        int a,b;
        cin>>a>>b;
        mov(root,a,b);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值