```c++
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
typedef int type;
typedef struct treeNode {
type data;
treeNode* left;
treeNode* right;
}treeNode;
treeNode* creatBinTree(vector<int> arr) {
queue q;
if (arr.empty()) {
return nullptr;
}
treeNode* head = new treeNode; //创建头节点
head->data = arr[0]; //存放数组首元素
q.push(head); //入队
treeNode* bt;
int i = 1;
while (!q.empty()) {
bt = q.front(); //取出头节点,准备给它安排左右孩子
q.pop(); //头节点出队,每一次新的循环,都让头出队
//先弄左孩子
//i只要不超过数组的有效长度,就有左孩子
if (i < arr.size()) {
if (arr[i] == 0)
{
bt->left = nullptr;
i++;
}
else
{
bt->left = new treeNode;
bt->left->data = arr[i];
q.push(bt->left); //左孩子入队
i++; //数组后移
}
}
else {
bt->left = nullptr;
}
//再弄右孩子
if (i < arr.size()) {
if (arr[i] == 0)
{
bt->right = nullptr;
i++;
}
else {
bt->right = new treeNode;
bt->right->data = arr[i];
q.push(bt->right); //右孩子入队
i++; //数组后移
}
}
else {
bt->right = nullptr;
}
}
return head; //最后队列为空就出while,返回头节点
}
treeNode* anc(treeNode* root, int p, int q)
{ if (root->data == q || root->data == p || root== nullptr) {return root};
treeNode* left = anc(root->left, p, q);
treeNode* right = anc(root->right, p, q);
if (left != nullptr && right != nullptr)
{return root; }
if (left ==nullptr)
{ return right; }
return left;
}
int main() {
vector<int> a;
a.push_back(20);
a.push_back(5);
a.push_back(15);
a.push_back(4);
a.push_back(9);
a.push_back(13);
a.push_back(17);
a.push_back(2);
a.push_back(0);
a.push_back(8);
a.push_back(0);
a.push_back(12);
a.push_back(14);
a.push_back(16);
a.push_back(18);
a.push_back(1);
a.push_back(3);
treeNode* tou = creatBinTree(a);
cout<left->right->left->data;
cout<<anc(tou, 2, 18)->data;
}
```
树如何找共同祖先_树的基础知识
https://blog.csdn.net/weixin_28756413/article/details/112150741
C++处理输入流中以逗号或者空格分隔的数据
https://blog.csdn.net/qq_34525916/article/details/121379665
可以借鉴下