是二叉树问题
这是出现的情况
这是部分代码
//键盘输入一个元素x,求其父节点、兄弟结点、子结点的值,不存在时给出相应提示信息。对兄弟结点和孩子结点,存在时要明确指出是左兄弟、左孩子、右兄弟或右孩子
template<class ElementType>
void BiTree<ElementType>::GetFatherBrotherChildNode(Node <ElementType>* T, ElementType x)
{
if (T)
{
if (T->lChild != NULL)
{
if (T->lChild->data == x)
{
cout << "父节点的值为:" << T->data << endl; //输出父节点的值
if (T->rChild == NULL)
{
cout << "右兄弟不存在!" << endl; //判断右兄弟是否存在,存在输出其值
}
else {
cout << "右兄第为:" << T->rChild->data << endl;
}
if (T->lChild->lChild == NULL)
{
cout << "左孩子不存在!" << endl;
}
else {
cout << "左孩子为:" << T->lChild->lChild->data << endl;
}
if (T->lChild->rChild == NULL)
{
cout << "右孩子不存在!" << endl;
}
else {
cout << "右孩子为:" << T->lChild->lChild->data << endl;
}
}
}
if (T->rChild != NULL)
{
if (T->rChild->data == x)
{
cout << "父节点的值为:" << T->data << endl; //输出父节点的值
if (T->lChild == NULL)
{
cout << "左兄弟不存在!" << endl; //判断左兄弟是否存在,存在输出其值
}
else {
cout << "左兄第为:" << T->lChild->data << endl;
}
if (T->rChild->lChild == NULL)
{
cout << "左孩子不存在!" << endl;
}
else {
cout << "左孩子为:" << T->rChild->lChild->data << endl;
}
if (T->rChild->rChild == NULL)
{
cout << "右孩子不存在!" << endl;
}
else {
cout << "右孩子为:" << T->rChild->rChild->data << endl;
}
}
}
GetFatherBrotherChildNode(T->lChild, x);
GetFatherBrotherChildNode(T->rChild, x);
}
}
你这里判断右孩子不存在 ,但是输出的是左孩子
else {
cout << "右孩子为:" << T->lChild->lChild->data << endl;
}
应该改成
cout << "右孩子为:" << T->lChild->rChild->data << endl; // 第二个 lChild 换成 rChild