如何从后缀表达式生成表达式树

How to make expression tree from postfix expression?

本文关键字:表达式 后缀      更新时间:2023-10-16

我想用C++创建树。我可以在没有错误或警告的情况下编译代码,但我没有得到输出。

我认为错误是在过度fn,但不知道如何消除这一点。

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
struct tree
{
int data;
struct tree * left;
struct tree * right;
};
typedef struct tree * TREE;
TREE maketree(int x)
{
TREE tree = (TREE)malloc(sizeof(tree));
if(tree == NULL)
{
return NULL;
}
tree->left = tree->right = NULL;
tree->data = x;
return tree;
}
void setleft(TREE tree,int x)
{
if(tree == NULL || tree->left != NULL)
{
cout<<"t Error !! Inserting New Node At Left Side  !n";
}
else
{
tree->left = maketree(x);
}
}
void setright(TREE tree,int x)
{
if(tree == NULL || tree->right != NULL)
{
cout<<"t Error !! Inserting New Node At Right Side !n";
}
else
{
tree->right = maketree(x);
}
}
void inorder(TREE root)
{
if(root != NULL)
{
TREE left=root->left;
TREE right=root->right;
inorder(left);
cout<<root->data;
inorder(right);
}
}
void main()
{
clrscr();
TREE root = NULL,child,parent;
int i,j = 1;
cout<<"Root Of Binary Search Tree :- ";
cin>>i;
root = maketree(i);
cout<<"nn";
while(i)
{
cout<<j<<" Node Value:- ";
cin>>i;
if(i < 0)
{
break;
}
parent = child = root;
while((i != parent->data) && (child != NULL))
{
parent = child;
if(i < parent->data)
{
child = parent->left;
}
else
{
child = parent->right;
}
}
if(i == parent->data)
{
cout<<"t Value "<<i<<" Already Present In BST !!n";
}
else if(i < parent->data)
{
setleft(parent,i);
}
else
{
setright(parent,i);
}
j++;
}
inorder(root);
getch();
}

如果您想用C++编写,那么就用C++编写。使用构造函数、析构函数和类方法。可能会将您的数据成员设为私人成员。使用new而不是malloc,析构函数可能会想要删除(树的子节点)。

您所写的是C语言,而不是包含了C++最糟糕的功能iostream,以及旧的不推荐使用的非标准版本。

这看起来像是学校的练习。

我也看不到你用malloc分配的数据在哪里free

排序逻辑应该在基于树的函数中,而不是在main中。

您的"错误"可能是输出中缺少空白,但我不知道。

tree同时用作数据类型(它是一个结构,在C++中不需要使用struct进行限定)和变量(经常使用它)是合法的,但不是很好的做法。

好的,现在是一些代码,主要基于您的代码。

class tree
{
tree * left;
tree * right;
int value;
public:
explicit tree( int v );
~tree();
bool insert( int v );
void print( std::ostream& ) const;
private:
tree( const tree& );
tree& operator=( const tree& );
};
tree::tree( int v ) : 
left( NULL ), 
right( NULL ),
value( v )
{
}
tree::~tree()
{
delete right;
delete left;
}
bool tree::insert( int v )
{
// inserts v in the correct place in the tree, returns true
// if it inserted or false if it already exists
// I want you to fill in the detail for this function
}
void tree::print( std::ostream& os ) const
{
// prints the tree
if( left )
{
left->print( os );
}
os << value << 'n';
if( right )
{
right->print( os );
}
}

在这里,我留下了一个功能供您执行。您不需要实现私有复制构造函数或赋值运算符。

同时执行main()。请注意,不需要在堆上实现main中的树(使用new)。在堆栈上实现它。

main()将读取数字,将它们插入到调用其insert()方法的树中,然后在最后打印树,将std::cout作为参数传递。

你需要#include <iostream>(而不是iostream.h),它就会工作。