簡體   English   中英

二叉樹(非二叉搜索樹)創建新節點和子節點

[英]Binary Tree (Not Binary Search Tree) Creating New Node and Children

我正在嘗試實現一種方法來創建要插入到二叉樹(不是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;
            }
}

我面臨的問題是當我使用遞歸方法創建左孩子或右孩子時。 我認為這並不指向首先創建的父節點的值。 我是對還是錯? 我想問題是我是否要使用要實現的方法將父節點鏈接到右側或左側子節點。

createNewNode()函數中,您只需創建一個新節點並保留它而不將它們彼此關聯! 您應該將其綁定到左或右指針。

這是您應該做的:

  1. 將此函數的輸出從void更改為n
  2. 在函數末尾,返回新創建的節點
  3. 在兩個switch語句中,您在其中遞歸調用函數,分別將函數調用的輸出分配給newnode->leftnewnode->right

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM