[英]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()
函數中,您只需創建一個新節點並保留它而不將它們彼此關聯! 您應該將其綁定到左或右指針。
這是您應該做的:
void
更改為n
newnode->left
或newnode->right
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.