所以我需要使用递归实现二叉搜索树的成员函数、前序和中序遍历。我在实现这三个方面都遇到了麻烦,因为它们的输出错误。遍历应该将它遇到的数据值添加到给定的链表中。
我的成员函数只打印出树的正确节点。我附上了我的代码,如果有人能给我一些关于错误所在的位置以及为什么输出没有打印出它应该是的内容的指示,那就太棒了。提前致谢!!!
我目前得到的输出:
size of test BinaryTree: 11
member true for 8
member true for 38
member true for 39
member true for 45
pre order: [8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 38, 38, 38, 38, 38, 38, 38, 38, 39, 39, 45, 45]
in order: [8, 8, 8, 8, 38, 38, 38]
我想要的输出:
size of test BinaryTree: 11
member true for 1
member true for 3
member true for 4
member true for 7
member true for 8
member true for 16
member true for 31
member true for 33
member true for 38
member true for 39
member true for 45
pre order: [8, 4, 3, 1, 7, 38, 31, 16, 33, 39, 45]
in order: [1, 3, 4, 7, 8, 16, 31, 33, 38, 39, 45]
我的代码:
bool BinaryTreeNode::member(Data * newData) {
if (newData->compareTo(this->nodeData) == 0) {
return true;
}
else if (newData->compareTo(this->nodeData) == -1) {
if (left == NULL)
return false;
else
return left->member(newData);
}
else if (newData->compareTo(this->nodeData) == 1) {
if (right == NULL)
return false;
else
return right->member(newData);
}
return false;
}
void BinaryTreeNode::preorderTraversal(LinkedList * result) const {
result->insert(nodeData);
if (left != NULL) left->preorderTraversal(result);
result->insert(nodeData);
if (right != NULL) right->preorderTraversal(result);
}
void BinaryTreeNode::inorderTraversal(LinkedList * result) const {
if (left != NULL) {
left->inorderTraversal(result);
result->insert(nodeData);
}
if (right != NULL) {
right->inorderTraversal(result);
}
}