二叉树的创建以及寻找两个节点的最近公共祖先
通过输入一个按照先序遍历得出的字符串,‘#’代表空的子节点,大写字母代表节点内容,来进行二叉树的构建
输入两个节点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