c++ - 二叉树(不是二叉搜索树)创建新节点和子节点

标签 c++ binary-tree dev-c++

我正在尝试实现一种创建节点以插入二叉树(不是 bst)的方法。

struct node{
       struct node *left;
       int data;
       struct node *right;
};

typedef struct node *n;

void createNewNode() {

     char r; // stands for response (whether or not a left or right child should be created)
     int d; //data to be stored in a node

     n newnode = new(struct node); //creates a new node

     cout<<"Enter data for the new node:"<<endl;
     cin>>d;
     newnode->data = d;

     cout<<"any left child? y/n"<<endl;
     cin>>r;
     switch (r) {
            case 's':
                 createNewNode(); // I thought to make it recursive and if a child is going to be created, then the method will call itself all over again
                 break;

            case 'n':
                 newnode->left = NULL; // if child is not created then pointer is NULL
                 break;
            }

     cout<<"any right child? y/n"<<endl;
     cin>>r;
     switch (r) {
            case 's':
                 createNewNode(); //recursive method again
                 break;

            case 'n':
                 newnode->right = NULL; // if child is not created then pointer is NULL
                 break;
            }
}

我面临的问题是当我使用递归方法创建左 child 或右 child 时。我认为它没有指向首先创建的父节点的值。我是对还是错?我想问题是我是否正在使用我尝试实现的方法将父节点链接到右子节点或左子节点。

最佳答案

createNewNode() 函数中,您只需创建一个新节点并保留它,而无需将它们相互关联!您应该将它绑定(bind)到左指针或右指针。

这是你应该做的:

  1. 将此函数的输出从 void 更改为 n
  2. 在函数结束时返回新创建的节点
  3. 在递归调用函数的两个 switch 语句中,相应地将函数调用的输出分配给 newnode->leftnewnode->right

关于c++ - 二叉树(不是二叉搜索树)创建新节点和子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16627563/

相关文章:

c++ - 在具有后缀树的 LZ77/LZSS 上匹配重叠前瞻

c++ - 使用 glTexCoordPointer() 的问题

c++ - 创建一个循环,将输出所有大于零且小于 60(不包括 60)的 5 的倍数

c++ - 我可以直接在VC9项目中使用用VC6构建的C风格库吗?

c++ - 创建静态哨兵节点的正确方法是什么

algorithm - 查找给定 n 个键的二叉树数量的变体

c++ - 如何在 BST 中找到和与给定值相同的两对?

java - 插入二叉树问题的方法

c - DEVC++ 中的错误(比较字符串和字符)

c++ - 开发 C++ (Mingw) 堆栈限制