对不起,这是我第一次在stackoverflow中提问。我刚读了常见问题并且知道我不遵守规则。我不只是在处理和粘贴问题。我使用有序遍历方法来进行递归,并检查节点是否是五的倍数,我不知道接下来该做什么。我应该用旗帜检查一下吗?
void findNodes(BSTNode<Key,E> *root) const
{
if(root==NULL) return;
else
{
if(root->key()%5==0)//I know it's wrong, but I don't know what to do
{
findNodes(root->left());
cout<<root->key()<<" ";
findNodes(root->right());
}
else
{
findNodes(root->left());
findNodes(root->right());
}
}
}
答案 0 :(得分:1)
祖父素为5的倍数的打印节点很复杂,因为您必须查看树的“向上”。如果你把问题看作是找到5的倍数的所有节点并打印他们的孙子就更容易了,因为你只需要沿着树走下去。
void printGrandChildren(BSTNode<Key,E> *root,int level) const{
if(!root) return;
if(level == 2){
cout<<root->key()<<" ";
return;
}else{
printGrandChildren(root->left(),level+1);
printGrandChildren(root->right(),level+1);
}
}
然后将findNodes修改为
void findNodes(BSTNode<Key,E> *root) const
{
if(root==NULL) return;
else
{
if(root->key()%5==0)
{
printGrandChildren(root,0);
}
else
{
findNodes(root->left());
findNodes(root->right());
}
}
}
答案 1 :(得分:0)
试试这个:
int arr[height_of_the_tree]; //arr[10000000] if needed;
void findNodes(BSTNode<Key,E> *root,int level) const {
if(root==NULL) return;
arr[level] = root -> key();
findNodes(root -> left(), level + 1);
if(2 <= level && arr[level - 2] % 5 == 0) cout << root->key() << " ";
findNodes(root -> right(), level + 1);
}
int main() {
...
findNodes(Binary_search_tree -> root,0);
...
}
答案 2 :(得分:0)
如果你只是试图打印我们所有的子节点,这些节点的祖先的密钥是5的倍数,那么一种方法就是将bool
传递给你的findNodes函数,该函数存储了这个事实。
有些事情:
void findNodes(BSTNode<Key,E>* node, bool ancesterIsMultOf5) const
{
if (node)
{
if (ancesterIsMultOf5)
std::cout << node->key() << std::endl;
ancesterIsMultOf5 |= (node->key() % 5 == 0);
findNodes(node->left(), ancesterIsMultOf5);
findNodes(node->right(), ancesterIsMultOf5);
}
}
或者,如果您正在尝试绘制树,则之前已经回答过:C How to "draw" a Binary Tree to the console
答案 3 :(得分:0)
替换以下
cout<<root->key()<<" ";
与
if(root->left)
{
if(root->left->left)
cout<<root->left->left->key()<< " ";
if(root->left->right)
cout<<root->left->right->key()<< " ";
}
if(root->right)
{
if(root->right->left)
cout<<root->right->left->key()<< " ";
if(root->right->right)
cout<<root->right->right->key()<< " ";
}