【问题标题】:Display function of Binary Tree is not working properly二叉树显示功能不正常
【发布时间】:2020-04-26 08:32:35
【问题描述】:

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

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

【问题讨论】:

  • 请详细描述您的问题。

标签: c++ recursion display


【解决方案1】:

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

正确的实现

node *create(){
    int x;
    cout << "Enter data(-1 for NULL): ";
    cin >> x;
    if(x == -1)
        return NULL;
    node* new_node = new node(x); // Create new node
    cout << "Enter left child: ";
    new_node -> left = create(); // Assign left child
    cout << "Enter right child: ";
    new_node -> right = create(); // Assign right child
    p = new_node; // Assign root of tree to p
    return new_node;
}

【讨论】:

  • 感谢您让我知道。你能帮我吗...如何询问用户是否需要将值分配给左孩子或右孩子...
  • 您可以将choice 变量作为输入。现在,if(choice=='L') new_node -&gt; left = create(); else new_node -&gt; right = create();
猜你喜欢
  • 1970-01-01
  • 2019-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
相关资源
最近更新 更多