Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/141.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 二叉树的显示功能工作不正常_C++_Recursion_Display - Fatal编程技术网

C++ 二叉树的显示功能工作不正常

C++ 二叉树的显示功能工作不正常,c++,recursion,display,C++,Recursion,Display,我为二叉树创建了一个程序。由于某种原因,我无法正确显示它。请帮我用正确的格式写下来。这是代码,如果还有其他错误,请告诉我 #include <iostream> using namespace std; class node { public: int data; node *left, *right; node(int x) { data = x; left = right = NULL; } }; clas

我为二叉树创建了一个程序。由于某种原因,我无法正确显示它。请帮我用正确的格式写下来。这是代码,如果还有其他错误,请告诉我

#include <iostream>
using namespace std;

class node
{
public:
    int data;
    node *left, *right;
    node(int x)
    {
        data = x;
        left = right = NULL;
    }
};
class tree
{
public:
    node *p;    
    node *create()
    {
        int x;
        cout << "Enter data(-1 for NULL): ";
        cin >> x;
        if(x == -1)
            return NULL;
        p = new node(x);
        cout << "Enter left child: ";
        p -> left = create();
        cout << "Enter right child: ";
        p -> right = create();
        return p;
    }
    void display1()
    {
        display(p);
    }
    void display(node *root)
    {
        if(root != NULL)
        {
            display(root -> left);
            cout << " " << root -> data << " ";
            display(root -> right);
        }
    }
};
int main()
{
    tree t;
    t.create();
    t.display1();
    return 0;
}
#包括
使用名称空间std;
类节点
{
公众:
int数据;
节点*左,*右;
节点(int x)
{
数据=x;
左=右=空;
}
};
类树
{
公众:
节点*p;
节点*create()
{
int x;
cout>x;
如果(x==-1)
返回NULL;
p=新节点(x);
cout left=create();
cout right=create();
返回p;
}
void display1()
{
显示器(p);
}
无效显示(节点*根)
{
if(root!=NULL)
{
显示(根->左);

cout问题在于
create()
成员函数。更具体地说,行
p=new node(x);
是一个问题,因为
p
是一个数据成员,应该指向树的根,但在每次递归调用时都将其分配给新节点,从而在以前的递归调用中有效地丢失节点。这会导致在调用
display
函数时出现错误/意外的输出,因为
p
不是指向树根

正确实施

节点*create(){
int x;
cout>x;
如果(x==-1)
返回NULL;
node*new_node=new node(x);//创建新节点
cout left=create();//分配左子对象
cout right=create();//分配正确的子项
p=new_node;//将树的根分配给p
返回新的_节点;
}

问题在于
create()
成员函数。更具体地说,行
p=new node(x);
是一个问题,因为
p
是一个数据成员,应该指向树的根,但在每次递归调用时都将其分配给新节点,从而在以前的递归调用中有效地丢失节点。这会导致在调用
display
函数时出现错误/意外的输出,因为
p
不是指向树根

正确实施

节点*create(){
int x;
cout>x;
如果(x==-1)
返回NULL;
node*new_node=new node(x);//创建新节点
cout left=create();//分配左子对象
cout right=create();//分配正确的子项
p=new_node;//将树的根分配给p
返回新的_节点;
}

请详细描述您的问题。请详细描述您的问题。感谢您让我知道它。您还可以帮助我解决…如何询问用户是否需要将值分配给左边的子节点或右边的子节点…您可以将
选择
变量作为输入。现在,
如果(选择='L')新建节点->左边=创建();else new_node->right=create();
。感谢您让我知道这一点。您还可以帮助我…如何询问用户是否需要将值分配给左边的子节点或右边的子节点…您可以将
choice
变量作为输入。现在,
if(choice='L')new_node->left=create();else new_node->right=create();