以C++打印BST的功能

Function to print BST in C++

本文关键字:功能 BST 打印 C++      更新时间:2023-10-16

Helo, 我正在寻找帮助,以尽可能轻松地编写我理解以漂亮的方式打印出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;
}

我正在寻求帮助,但我正在开始我的编程冒险,所以请不要生我的气:)谢谢!

编辑

我已经尝试了下面的函数,但它没有在顶部写入节点根,因为它应该是:/

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);
}
}

}

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

将"新建"更改为"新建1"编译程序。