C++ 二叉树(非二叉搜索树)创建新节点和子节点

C++ 二叉树(非二叉搜索树)创建新节点和子节点,c++,binary-tree,dev-c++,C++,Binary Tree,Dev C++,我正在尝试实现一种方法来创建一个节点以插入到二叉树(不是bst)中 struct节点{ 结构节点*左; int数据; 结构节点*右; }; typedef结构节点*n; void createNewNode(){ char r;//表示响应(是否应创建左或右子级) int d;//要存储在节点中的数据 n newnode=new(struct node);//创建一个新节点 cout在createNewNode()函数中,您只需创建一个新节点并将其保留,而不将它们彼此关联!您应该将其绑定到左或右

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

struct节点{
结构节点*左;
int数据;
结构节点*右;
};
typedef结构节点*n;
void createNewNode(){
char r;//表示响应(是否应创建左或右子级)
int d;//要存储在节点中的数据
n newnode=new(struct node);//创建一个新节点
cout在
createNewNode()
函数中,您只需创建一个新节点并将其保留,而不将它们彼此关联!您应该将其绑定到左或右指针

这就是你应该做的:

  • 将此函数的输出从
    void
    更改为
    n
  • 在函数末尾,返回新创建的节点
  • 在递归调用函数的两个switch语句中,相应地将函数调用的输出分配给
    newnode->left
    newnode->right
  • 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;
                }
    }