二叉树的创建以及寻找两个节点的最近公共祖先

二叉树的创建以及寻找两个节点的最近公共祖先

通过输入一个按照先序遍历得出的字符串,‘#’代表空的子节点,大写字母代表节点内容,来进行二叉树的构建

输入两个节点x和y,求解距离他们最近的共同祖先,若没有共同祖先则输出NULL

代码如下:

#include<stdio.h>
#include<stdlib.h>
#include<bits/stdc++.h>
using namespace std;
typedef struct BiTNode
{
    char data;
    struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;

void CreateBiTree(BiTree *T)
{
    char ch;
    scanf("%c",&ch);
    if(ch=='#')
        *T=NULL;
    else
    {
        *T=(BiTree  )malloc(sizeof(BiTNode));
        if(!*T)
            exit(-1);
        (*T)->data=ch;
        CreateBiTree(&(*T)->lchild);
        CreateBiTree(&(*T)->rchild);
    }
}
bool findPath(BiTNode *root, vector<char> &path, char k)
{
    if (root == NULL) return false;
    path.push_back(root->data);
    if (root->data == k)
        return true;
    if ( (root->lchild && findPath(root->lchild, path, k)) ||
         (root->rchild && findPath(root->rchild, path, k)) )
        return true;
    path.pop_back();
    return false;
}
void findLCA(BiTNode *root, char n1, char n2)

{
    vector<char> path1, path2;
    if ( !findPath(root, path1, n1) || !findPath(root, path2, n2))

          cout<<"NULL";
    int i;
    for (i = 0; i < path1.size() && i < path2.size() ; i++)
        if (path1[i] != path2[i])
            break;
    cout<<path1[i-1];
}
int main()
{
    BiTree T;
    CreateBiTree(&T);
    char a1,a2;
    cin>>a1>>a2;
    findLCA(T,a1,a2);
    return 0;
}

测试样例及运行结果:
在这里插入图片描述

本文参考博客:

https://blog.csdn.net/lwhsyit/article/details/82319751
https://blog.csdn.net/dream0130__/article/details/80779486?utm_medium=distribute.pc_relevant.none-task-blog-baidujs-1

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值