寻找双亲结点
BtNode* FindParent(BtNode* root, BtNode* pos)
{
if (root == NULL || pos == NULL)
return NULL;
if (root->leftchild == pos || root->rightchild == pos)
{
return root;
}
else
{
BtNode* p = FindParent(root->leftchild, pos);
if (p == NULL)
{
p = FindParent(root->rightchild, pos);
}
return p;
}
}
查找val值
BtNode* Find(BtNode* p, Element val)
{
if (p == NULL || p->data == val)
{
return p;
}
else
{
BtNode* q = Find(p->leftchild, val);
if (q == NULL)
{
q = Find(p->rightchild, val);
}
return q;
}
}
BtNode* FindValue(BtNode* p, Element val)
{
if (p == NULL) return NULL;
else
{
return Find(p, val);
}
}
二叉树空间释放
void Clear(BtNode* p)
{
if (p != NULL)
{
Clear(p->leftchild);
Clear(p->rightchild);
delete p;
}
}
计算二叉树结点个数
int BtCount(BtNode* p)
{
if (p == NULL)
return 0;
return BtCount(p->leftchild) + BtCount(p->rightchild) + 1;
}
计算二叉树的深度
int Highth(BtNode* p)
{
if (p == NULL) return 0;
else
{
return std::max(Highth(p->leftchild), Highth(p->rightchild)) + 1;
}
}
水平遍历(层次)
void LevelOrder(BtNode* p)
{
if (p == NULL) return;
queue<BtNode*> qu;
qu.push(p);
while (!qu.empty())
{
p = qu.front();
qu.pop();
cout << p->data << " ";
if (p->leftchild != NULL)
{
qu.push(p->leftchild);
}
if (p->rightchild != NULL)
{
qu.push(p->rightchild);
}
}
}
Z型遍历
void ZPrint(BtNode* p)
{
if (NULL == p)
return;
stack<BtNode*> ast;
stack<BtNode*> bst;
ast.push(p);
while (!ast.empty() || !bst.empty())
{
while (!ast.empty())
{
p = ast.top();
ast.pop();
cout << p->data << " ";
if (p->leftchild != NULL)
{
bst.push(p->leftchild);
}
if (p->rightchild != NULL)
{
bst.push(p->rightchild);
}
}
while (!bst.empty())
{
p = bst.top();
bst.pop();
cout << p->data << " ";
if (p->rightchild != NULL)
{
ast.push(p->rightchild);
}
if (p->leftchild != NULL)
{
ast.push(p->leftchild);
}
}
}
}
判断是否是满二叉树
bool IsFullBt(BtNode* p)
{
if (NULL == p)
return false;
int k = Highth(p);
return BtCount(p) == (int)(pow(2, k) - 1);
}
bool IsFullBt(BtNode* p)
{
if (NULL == p)
return false;
int s = 1;
bool tag = true;
queue<BtNode*> aqu;
queue<BtNode*> bqu;
aqu.push(p);
while (!aqu.empty() || !bqu.empty())
{
if (s != aqu.size())
{
tag = false;
break;
}
while (!aqu.empty())
{
p = aqu.front();
aqu.pop();
if(p->leftchild != NULL ) bqu.push(p->leftchild);
if (p->rightchild != NULL) bqu.push(p->rightchild);
}
s += s;
if (s != bqu.size())
{
tag = false;
break;
}
while (!bqu.empty())
{
p = bqu.front();
bqu.pop();
if (p->leftchild != NULL) aqu.push(p->leftchild);
if (p->rightchild != NULL) aqu.push(p->rightchild);
}
s += s;
}
return tag;
}
判断是否是完全二叉树
bool IsCompleteBTree(BtNode* p)
{
if (NULL == p) return false;
bool tag = true;
queue<BtNode*> qu;
qu.push(p);
while (!qu.empty())
{
p = qu.front();
qu.pop();
if (p == NULL)
{
break;
}
qu.push(p->leftchild);
qu.push(p->rightchild);
}
while (!qu.empty())
{
p = qu.front();
qu.pop();
if (p != NULL)
{
tag = false;
break;
}
}
return tag;
}