LCA树两个节点最低公共祖先

本文探讨了一个在树结构中查找两个指定节点之间的共同路径的问题,并提供了实现算法的详细步骤。通过构建树结构并使用递归方法,本文展示了如何在树中定位和输出共享路径的节点值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

struct Tree
{
    Tree *pLeft;
    Tree *pRight;
    int nValue;
};

bool FindPath(Tree *root,int nFindValue,vector<int> &vec)
{
    if(root == NULL)
    {
        return false;
    }
    bool flag = false;//判断是否找到要找到的节点值(路径)
    vec.push_back(root->nValue); //将值放到vector中
    if(root->nValue == nFindValue)//如果找到返回 true ,此时上一层的 flag 为true
    {
        return true;
    }
    if(!flag && root->pLeft != NULL)//如果找到值了,flag 为true 就不会继续查找了
    {
        flag = FindPath(root->pLeft,nFindValue,vec);
    }
    if(!flag && root->pRight != NULL)//如果找到值了,flag 为true 就不会继续查找了
    {
        flag = FindPath(root->pRight,nFindValue,vec);
    }
    if(flag == false)//如果找到值了 , 此时的路径  不应该 从 vector中 删除
    {
        vec.pop_back();
    }
    return flag;
}
int PanDuan(Tree *root,int nFindValue1,int nFindValue2)
{
    vector<int> vec1,vec2;
    int nValue = -1;
    int flag1 = FindPath(root,nFindValue1,vec1);
    int flag2 = FindPath(root,nFindValue2,vec2);
    ////////////////////////////////////////////////
    for(int i=0;i<vec1.size();i++)
    {
        cout<<vec1[i]<<" ";
    }
    cout<<endl;
    for(int i=0;i<vec2.size();i++)
    {
        cout<<vec2[i]<<" ";
    }
    cout<<endl;
    ////////////////////////////////////////////////
    if(flag1 && flag2)
    {
        for(int i = 0 ; i< vec1.size()< vec2.size()?vec1.size():vec2.size();i++)
        {
            if(vec1[i] != vec2[i])
            {
                break;
            }
            else
            {
                nValue = vec1[i];
            }
        }
    }
    return nValue;
}
Tree *newNode(int nValue)
{
    Tree *temp = new Tree;
    temp->nValue = nValue;
    temp->pLeft = NULL;
    temp->pRight = NULL;
    return temp;
}
int main()
{
    Tree * root = newNode(1);
    root->pLeft = newNode(2);
    root->pRight = newNode(3);
    root->pLeft->pLeft = newNode(4);
    root->pLeft->pRight = newNode(5);
    root->pRight->pLeft = newNode(6);
    root->pRight->pRight = newNode(7);
    cout<<PanDuan(root,4,6)<<endl;
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值