树结构中的二叉搜索树输出

时间:2014-10-27 03:09:57

标签: c++ tree char binary-search-tree

我使用了这篇文章中的代码How to display binary search tree in console properly?。它符合我的IDE,但它没有打印任何东西,所以它基本上什么都没有。我希望它在树形结构中打印出来,就像我在这里发布的帖子一样。我想我的int main()中的printLevel函数的第三个参数的代码输入错了。 char * x =“”能正常工作吗?它确实给出了警告信息,但我不确定我是否做得对。

string printLevel(Node *pRoot, int level, string gap)
{
    if (level == 1)
    {
        if (pRoot == 0)
        {
            cout << ".. printLevel - " << pRoot << ": " << gap << "-" << gap << "\n";
            return gap + "-" + gap;
        }
        stringstream out;
        out << pRoot->data;
        //cout << ".. printLevel - " << pRoot << ": " << gap << pRoot->data << gap << "\n";
        return gap + out.str() + gap;
    }
    else if(level > 1)
    {
        string left = printLevel(pRoot ? pRoot->pLeft : 0, level - 1, gap);
        string right = printLevel(pRoot ? pRoot->pRight : 0, level - 1, gap);
        //cout << ".. printLevel - " << pRoot << ": '" << left << "', '" << right << "'\n";
        return left + " " + right;
    }
    else return
        "";
}


void printLevelOrder(Node* pRoot, int depth)
{
    for (int i = 1; i <= depth; i++)
    {
        string gap = "";
        for (int j = 0; j < pow(2, depth - i) - 1; j++)
        {
            gap += " ";
        }
        string levelNodes = printLevel(pRoot, i, gap);
        cout << levelNodes <<endl;
    }
}

中的

Node *pRoot = NULL;  
int inputValue = 0;  
char* gap = " ";

// Loop to read in input values
cout << "To build a BST enter positive integer values, followed by -1 \n";
while (inputValue != -1) 
{
    cin >> inputValue;
    if( inputValue != -1) 
    {
        insertIntoTree( pRoot, inputValue);
    }
}
cout << endl;

// Display the tree
printLevel(pRoot, inputValue, gap);
printLevelOrder(pRoot, inputValue);

0 个答案:

没有答案
相关问题