二叉树中的随机插入 如何在不使用模板类的情况下,从左向右随机插入元素,实现C++中的二叉树?这是我的插入函数。有人能指出这有什么不对吗?请提供您的建议 Node* insert(int data){ Node* temp=new Node();
二叉树中的随机插入二叉树中的随机插入 如何在不使用模板类的情况下,从左向右随机插入元素,实现C++中的二叉树?这是我的插入函数。有人能指出这有什么不对吗?请提供您的建议 Node* insert(int data){ Node* temp=new Node(); ,c++,binary-tree,C++,Binary Tree,二叉树中的随机插入 如何在不使用模板类的情况下,从左向右随机插入元素,实现C++中的二叉树?这是我的插入函数。有人能指出这有什么不对吗?请提供您的建议 Node* insert(int data){ Node* temp=new Node(); temp->data=data; if(root==NULL){ temp->left=temp->right=NULL; } else if(!temp->left){
如何在不使用模板类的情况下,从左向右随机插入元素,实现C++中的二叉树?这是我的插入函数。有人能指出这有什么不对吗?请提供您的建议
Node* insert(int data){
Node* temp=new Node();
temp->data=data;
if(root==NULL){
temp->left=temp->right=NULL;
}
else if(!temp->left){
temp->left=insert(data);
}
else if(!temp->right){
temp->right=insert(data);
}
return temp;
}
如果是
根->左
和根->右
而不是临时
,那么这两个是否应该是else?如果你想让这个函数像那样递归,你不应该也传递一个指向这个函数的指针吗?root
似乎不会通过递归传播。很可能您正在针对相同的值进行反复测试,以获得类似的结果。在没有模板类的情况下,无法对您应该做的事情提出很好的建议。“通过从左到右随机插入元素而不使用模板类”我不理解这一点。在构建二叉树之前,您可能想先看看什么是二叉树。我在代码中没有看到任何类型的值比较。