0

我写了一个二叉搜索树类,它有一个递归函数,可以按升序打印出所有元素。

template <typename T>
void BST<T>::printInOrder(BSTNode *t) const
{
    if( t == NULL ){
        return;
    }
    printInOrder( t->left );
    cout << t->element << " ";
    printInOrder( t-> right );
    cout << "\n"; // this is not correct 
}

一旦读取了最大值,我正在尝试添加一个新行。我怎样才能做到这一点?在其当前状态下,该函数仅打印 n 个新行,其中 n 是树中的节点数。

注意:这适用于规定在函数内调用换行符并且函数本身是递归的项目。

4

1 回答 1

1
  • 函数中添加了换行符
  • 函数必须是递归的

奇怪的要求,但鉴于此,这是一种方法:

template <typename T>
void BST<T>::printInOrder(BSTNode *t, bool addNewline) const
{
    if( t == NULL ){
        return;
    }
    printInOrder( t->left, false );
    cout << t->element << " ";
    printInOrder( t-> right, false );
    if( addNewLine )
        cout << "\n";
}

// ...somewhere else...
bst.printInOrder(node, true);

但实际上,您应该使用两个函数,或者自己添加换行符:

bst.printInOrder(node);
cout << "\n";
于 2013-04-02T23:24:56.483 回答