C++ 用于在C+中打印BST的函数+;

C++ 用于在C+中打印BST的函数+;,c++,struct,binary-search-tree,C++,Struct,Binary Search Tree,你好, 我正在寻找帮助,以编写尽可能简单,让我理解的功能,以打印出漂亮的方式BST。像 50 / \ 30 70 下面是我向树中添加元素的代码: #include <iostream> using namespace std; struct node { int key; struct node *left; struct node *right; }; struct node *root; struct node *make_leaf(in

你好, 我正在寻找帮助,以编写尽可能简单,让我理解的功能,以打印出漂亮的方式BST。像

  50
 /  \
30  70
下面是我向树中添加元素的代码:

#include <iostream>

using namespace std;

struct node
{
    int key;
    struct node *left;
    struct node *right;
};
struct node *root;

struct node *make_leaf(int new_data);
struct node *add_node(struct node* root, int key);

int main()
{
   node *root = NULL;
   int new_element, how;
   cout<<"How many elements?"<<endl;
   cin>>how;
   for(int i=0; i<how; ++i){
   cout<<"Enter element value"<<endl;
   cin>>new_element;
   root = add_node(root, new_element);
   }
return 0;
}
struct node* make_leaf(int new_data){
       node *nd=new node;
       nd->key=new_data;
       nd->left=NULL;
       nd->right=NULL;
       return nd;

}
struct node *add_node(struct node* root, int key){
    if (root==NULL)
    {
        return make_leaf(key);
    }
    else
    {
        if (root->key > key)
        {
            root->left = add_node(root->left, key);
        }
        else
        {
            root->right = add_node(root->right, key);
        }
    }
    return root;
 }
#包括
使用名称空间std;
结构节点
{
int键;
结构节点*左;
结构节点*右;
};
结构节点*根;
结构节点*make_leaf(int new_数据);
结构节点*添加_节点(结构节点*根,int键);
int main()
{
node*root=NULL;
int新元素,如何;
cout键)
{
root->left=添加_节点(root->left,键);
}
其他的
{
root->right=添加_节点(root->right,key);
}
}
返回根;
}
我正在寻求帮助,但我将从编程开始我的冒险,所以请不要对我生气:)谢谢

编辑

我尝试了下面的函数,但它没有像应该的那样在顶部写入节点根:/

void postorder(struct node * root, int indent)
{
    if(root != NULL) {

        if(root->right) {
            postorder(root->right, indent+4);
        }
        if (indent) {
            cout << setw(indent) << ' ';
        }
        if (root->right) cout<<" /\n" << setw(indent) << ' ';
        if(root->left) {
            cout << setw(indent) << ' ' <<" \\\n";
            postorder(root->left, indent+4);
        }
    }
void postorder(结构节点*根,整数缩进)
{
if(root!=NULL){
如果(根->右){
后订单(根->右,缩进+4);
}
如果(缩进){

coutnew是保留关键字。请将变量“new”的名称更改为其他名称


将new改为new1编译您的程序。

谢谢,完成:)但它仍然没有解决我的打印功能问题:/n如果您查看
postorder
函数,您将看到如果只有根节点,则该节点不会被打印。您需要重新访问
postorder
逻辑,因为它甚至不适用于simp避免树只有一个根节点的情况。可以从删除“奇特的缩进”内容开始,并在遍历过程中集中精力打印每个节点。