1151 LCA in a Binary Tree (30分)

110 篇文章 0 订阅

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.

Input Specification:
Each input file contains one test case. For each case, the first line gives two positive integers: M (≤ 1,000), the number of pairs of nodes to be tested; and N (≤ 10,000), the number of keys in the binary tree, respectively. In each of the following two lines, N distinct integers are given as the inorder and preorder traversal sequences of the binary tree, respectively. It is guaranteed that the binary tree can be uniquely determined by the input sequences. Then M lines follow, each contains a pair of integer keys U and V. All the keys are in the range of int.

Output Specification:
For each given pair of U and V, print in a line LCA of U and V is A. if the LCA is found and A is the key. But if A is one of U and V, print X is an ancestor of Y. where X is A and Y is the other node. If U or V is not found in the binary tree, print in a line ERROR: U is not found. or ERROR: V is not found. or ERROR: U and V are not found…

Sample Input:
6 8
7 2 3 4 6 5 1 8
5 3 7 2 6 4 8 1
2 6
8 1
7 9
12 -3
0 8
99 99
Sample Output:
LCA of 2 and 6 is 3.
8 is an ancestor of 1.
ERROR: 9 is not found.
ERROR: 12 and -3 are not found.
ERROR: 0 is not found.
ERROR: 99 and 99 are not found.

先通过前中序建立二叉树,然后对其进行lca,和bst的lca不同,普通二叉树的lca应该是想象成帮两个结点找父结点,因为这里给的是值,我一开始还想通过值找出node再做的,后面发现用值和结点值比较也行,因为这里都是不同的数字。
普通二叉树的lca需要有一个参数root,如果root为空,就返回空。如果root值等于u或者v就返回root,因为此时已经找到了,不然就去左右子树分别找,返回两个新定义的node,如果在左子树返回空,证明结果在右子树中,所以返回rchild,右子树反之。如果左右均不为空,证明两个结点分别在左右子树中,就返回root
最后返回null。
是否存在这个结点在一开始就用map记录好了

#include<iostream>
#include<vector>
#include<unordered_map>
#include<cstdio>
using namespace std;
struct node{
    int val;
    node* lchild, *rchild;
};
vector<int> inorder;
vector<int> preorder;
unordered_map<int,int> hashTable;
unordered_map<int,int> exist;//判断每个节点是否在树中可以找到

node* buildTree(int preL,int preR,int inL,int inR){
    if(preL > preR) return nullptr;
    node* root = new node;
    root->val = preorder[preL];
    root->lchild = root->rchild = nullptr;
    int leftSubTree = hashTable[preorder[preL]] - inL;
    root->lchild = buildTree(preL+1,preL+leftSubTree,inL,inL+leftSubTree-1);
    root->rchild = buildTree(preL+leftSubTree+1,preR,inL+leftSubTree+1,inR);
    return root;
}

node* lca(node* root,int u, int v){
    //找到第一个可以使uv结点位于左右两侧的子结点
    if(root == nullptr) return nullptr;
    if(root->val == u || root->val == v) return root;
    node* lchild = lca(root->lchild, u,v);
    node* rchild = lca(root->rchild, u,v);
    if(rchild == nullptr) return lchild;
    if(lchild == nullptr) return rchild;
    if(lchild != nullptr && rchild != nullptr) return root;
    return nullptr;
}

int main(){
    int m,n,x;
    cin>>m>>n;
    for(int i = 0; i < n; i++){
        cin>>x;
        exist[x]++;
        inorder.push_back(x);
    }
    for(int i = 0; i < n; i++){
        cin>>x;
        preorder.push_back(x);
    }
    for(int i = 0; i < n; i++){
        hashTable[inorder[i]] = i;//记录中序遍历每个结点的下标
    }
    node* root = new node;
    root = buildTree(0,n-1,0,n-1);
    //此时已经建树完成,接下来是lca
    int u,v;
    for(int i = 0; i < m; i++){
        cin>>u>>v;
        if(exist[u] == 0 && exist[v] == 0){
            printf("ERROR: %d and %d are not found.\n",u,v);
            continue;
        }
        else if(exist[u] == 0 || exist[v] == 0){
            printf("ERROR: %d is not found.\n",exist[u]==0 ? u:v);
            continue;
        }
        //给两个数字如何lca,先遍历这棵树,找到对应节点/根据值来和结点比较也行
        node* a = lca(root,u,v);
        if(a->val == u || a->val == v){
            printf("%d is an ancestor of %d.\n",a->val,a->val==u?v:u);
            continue;
        }
        else{
            printf("LCA of %d and %d is %d.\n",u,v,a->val);
        }
    }
    return 0;
}

这次算是真正想通了lca的问题,不要把lca当成找公共父亲结点,就把它当成找单个结点的父亲结点。可以自己画一下树来找就行了。
真正的递归边界:如果当前结点是空节点,就return,一开始忘记写了,一直段错误
虚假的边界:如果当前结点的值等于uorv,就return root
都没有的话,就定义两个node指针,分别取左右子树找,看看能不能找到u或者v,如果左右node均不为空,证明u和v分别在左右子树中。如果左不为空,就返回左,证明u和v都在左子树中。画图画图就想通了。

#include<vector>
#include<unordered_map>
#include<iostream>
#include<cstdio>
using namespace std;
int m,n;
vector<int> inOrder;
vector<int> preOrder;
unordered_map<int,int> exist;
unordered_map<int,int> ma;
struct node{
    int val;
    node* lchild, *rchild;
};

node* buildTree(int preL, int preR, int inL, int inR){
    if(preL>preR) return nullptr;
    node* root = new node;
    root->val = preOrder[preL];
    root->lchild = root->rchild = nullptr;
    int subLeftTree = ma[preOrder[preL]] - inL;
    root->lchild = buildTree(preL+1,preL+subLeftTree,inL,inL+subLeftTree-1);
    root->rchild = buildTree(preL+subLeftTree+1,preR,inL+subLeftTree+1,inR);
    return root;
}

node* lca(node* root, int u, int v){
    if(root == nullptr) return nullptr;
    if(root->val == u || root->val == v) return root;
    node* l = lca(root->lchild,u,v);
    node* r = lca(root->rchild,u,v);
    if(l != nullptr && r!=nullptr) return root;
    else if(l != nullptr) return l;
    else if(r!=nullptr) return r;
}

int main(){
    cin>>m>>n;
    inOrder.resize(n+1);
    preOrder.resize(n+1);
    for(int i = 0; i < n; i++){
        cin>>inOrder[i];
        exist[inOrder[i]]++;
    }
    for(int i = 0; i < n; i++){
        cin>>preOrder[i];
    }
    for(int i = 0; i < n; i++){
        ma[inOrder[i]] = i;
    }
    node* root = new node;
    root = buildTree(0,n-1,0,n-1);
    int u,v;
    for(int i = 0; i < m; i++){
        cin>>u>>v;
        if(exist[u] == 0 && exist[v] == 0){
            printf("ERROR: %d and %d are not found.\n",u,v);
            continue;
        }
        else if(exist[u] == 0 || exist[v] == 0){
            printf("ERROR: %d is not found.\n",exist[u] == 0 ? u:v);
            continue;
        }
        node* ancestor = lca(root,u,v);
        if(ancestor->val == u || ancestor->val == v){
            printf("%d is an ancestor of %d.\n",ancestor->val,ancestor->val == u ? v : u);
        }
        else{
            printf("LCA of %d and %d is %d.\n",u,v,ancestor->val);
        }
    }
    return 0;
}

定义两个node* l和r,分别是在左右子树中找,如果都不为空,证明当前结点就是lca,如果左边不为空,就直接return l,因为左不空右空,证明两个结点都在左子树里,l有可能是u有可能是v也有可能是他们的父结点,如果是u或者v的话,一定也是先返回高层的,所以l就是正确答案,直接返回l即可。右边不为空也是同理

//lac,建树然后递归查找,找当前结点的左右,如果左右均不为空,证明就是当前结点,如果左边不为空右边为空或者右边不为空左边空,也是当前结点
//用unordered_map来记录是否有这个结点
#include<iostream>
#include<vector>
#include<unordered_map>
#include<cstdio>
using namespace std;
struct node{
    int val;
    node* lchild, *rchild;
};
vector<int> inOrder;
vector<int> preOrder;
unordered_map<int,int> ma;
unordered_map<int,int> exist;

node* buildTree(int preL,int preR, int inL,int inR){
    if(preL > preR) return nullptr;
    node* root = new node;
    root->val = preOrder[preL];
    root->lchild = root->rchild = nullptr;
    int subLeftTree = ma[preOrder[preL]] - inL;
    root->lchild = buildTree(preL+1,preL+subLeftTree,inL,inL+subLeftTree-1);
    root->rchild = buildTree(preL+subLeftTree+1,preR,inL+subLeftTree+1,inR);
    return root;
}

node* lca(node* s,int u, int v){
    if(s == nullptr) return nullptr;
    if(s->val == u || s->val == v) return s;
    node* l = lca(s->lchild,u,v);
    node* r = lca(s->rchild,u,v);
    if(l != nullptr && r!=nullptr) return s;
    else if(l != nullptr) return l;//如果右子树为空,证明都在左子树里,而lca左子树第一个返回的结点,一定是比较高层的结点,就是父结点
    else if(r != nullptr) return r;
}

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];
        exist[inOrder[i]]++;
    }
    for(int i = 0; i < n; i++){
        cin>>preOrder[i];
    }
    for(int i = 0; i < n; i++){
        ma[inOrder[i]] = i;
    }
    node* root = new node;
    root = buildTree(0,n-1,0,n-1);
    int u,v;
    for(int i = 0; i < m; i++){
        cin>>u>>v;
        if(exist[u] == 0 && exist[v] == 0){
            printf("ERROR: %d and %d are not found.\n",u,v);
            continue;
        }
        else if(exist[u] == 0 || exist[v] == 0){
            printf("ERROR: %d is not found.\n",exist[u]==0?u:v);
            continue;
        }
        node* parent = lca(root,u,v);
        if(parent->val == u || parent->val == v){
            printf("%d is an ancestor of %d.\n",parent->val,parent->val == u?v:u);
        }
        else{
            printf("LCA of %d and %d is %d.\n",u,v,parent->val);
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值