#include <iostream>
#include <queue>
#include <vector>
using namespace std;
class btree
{
public:
char value;
btree *l;
btree *r;
btree(char val) : value(val), l(nullptr), r(nullptr){};
btree(char val, btree *lp, btree *rp) : value(val), l(lp), r(rp){};
};
struct items//这个是数据格式的要求,left和right是数组索引.
{
char value;
int left, right;
items(char val, int l, int r) : value(val), left(val), right(val){};
};
btree *build(char *arr, int cur, int len, char no) //树的节点数组,始点和终点,
//no是空节点标志字符
{
btree *root = nullptr;
if (cur >= len || arr[cur] == no)
{
return root;//如果不能再建立节点,就直接返回一个空节点
}
//否则就给节点赋值,并把左右子节点给确定下来,用到了递归,建议认真思考下。
root = new btree(arr[cur], build(arr, cur * 2 + 1, len, no), build(arr, cur * 2 + 2, len, no));
return root;
}
void pre(btree *root)//先序
{
if (root == nullptr)
{
return;
}
cout << root->value << endl;
pre(root->l);
pre(root->r);
}
void in(btree *root)
{
if (root == nullptr)
{
return;
}
pre(root->l);
cout << root->value << endl;
pre(root->r);
}
void aft(btree *root)
{
if (root == nullptr)
{
return;
}
pre(root->l);
pre(root->r);
cout << root->value << endl;
}
void layer(btree *root)//层序,非递归写起来比较好理解
{
queue<btree *> q1;
queue<btree *> q2;//第一层放q1,第二层从q1里衍生出来子节点放q2,反复如此
q1.push(root);
while (!q2.empty() || !q1.empty())
{
if (q2.empty())
{
while (!q1.empty())
{
btree *front = q1.front();
cout << front->value << ' ';
q1.pop();
if (front->l != nullptr)
{
q2.push(front->l);
}
if (front->r != nullptr)
{
q2.push(front->r);
}
}
}
else if (q1.empty())
{
while (!q2.empty())
{
btree *front = q2.front();
cout << front->value << ' ';
q2.pop();
if (front->l != nullptr)
{
q1.push(front->l);
}
if (front->r != nullptr)
{
q1.push(front->r);
}
}
}
cout << endl;
}
}
int getDepth(btree *p)//节点p的子树深度
{
if (p == nullptr)
{
return 0;
}
return max(getDepth(p->l), getDepth(p->r)) + 1;
}
bool isSame(const btree *q1, const btree *q2)//判断q1,q2是否同构,拍脑袋想出来的,不知道对不对,感觉挺合理的,网上的版本结构太复杂了
{
if (q1 == nullptr && q2 == nullptr)
return true;
if (q1 != nullptr && q2 == nullptr || q2 != nullptr && q1 == nullptr)
return false;
return q1->value == q2->value && ((isSame(q1->l, q2->r) && isSame(q1->r, q2->l)) || (isSame(q1->l, q2->l) && isSame(q1->r, q2->r)));
}
C++数据结构根据数组建立链式二叉树
最新推荐文章于 2024-01-27 17:44:12 发布