[英]iteratively insert into a binary search tree.Debug C++ code
这是一个C ++函数,用于从整数数组创建BST树?
这很简单。
以第一个元素为根。
获取下一个数组元素并将其插入树中。
为什么循环从i = 2开始而不是i = 1?
node* buildtree(int a[], int len)
{
node* root=new node(a[0]);
node* temp=root;
for(int i=1;i<len;i++)
{
while(!(root->left==NULL && root->right==NULL))
{
cout<<"here"<<i<<" "<<a[i]<<" " << root->val<<"\n";
if(root->val>a[i])
root=root->left;
else
root=root->right;
}
node* currnode=new node(a[i]);
if(root->val>a[i])
root->left=currnode;
else
root->right=currnode;
if(root==NULL)
cout<<"error...never.here";
root=temp;
}
return root;
}
非常感谢您对它的解释。我尝试了另一种方法,但它只能找到根,这是什么问题?
node* buildtree(int a[],int len)
{ node* root=new node(a[0]);
node* curr;
for(int i=1;i<len;i++)
{ curr=root;
while(curr!=NULL)
{
if(curr->val>a[i])
curr=curr->left;
else
curr=curr->right;
}
curr=new node(a[i]);
}
return root;
}
因为在循环的第一次迭代中, while
条件不成立,因为根节点没有子节点。
while(!(root->left==NULL && root->right==NULL)
对于i = 1,左侧和右侧节点为NULL,并且左侧节点在第一次迭代结束时填充。
当试图找到插入点时,
while(!(root->left==NULL && root->right==NULL))
{
cout<<"here"<<i<<" "<<a[i]<<" " << root->val<<"\n";
if(root->val>a[i])
root=root->left;
else
root=root->right;
}
仅当两个子项都为NULL
时才停止,因此在某些时候,您将root
设置为NULL
。 考虑数组以[5, 3, 6, ... ]
开头。 你开始
NULL <- node(5) -> NULL
node(3) <- node(5) ->NULL
然后尝试插入3。由于不是两个孩子都为NULL
,所以while
循环运行
if (5 > 7) // false
root = root->left;
else
root = root->right; // now root == NULL, oops
并重新检查控制条件
while(!(NULL->left == NULL && NULL->right == NULL))
segfault可能在这里调用未定义的行为。
你应该做类似的事情
while(true) {
if (root->val > a[i]) {
if (root->left == NULL) {
root->left = new node(a[i]);
break;
} else {
root = root->left;
}
} else {
if (root->right == NULL) {
root->right = new node(a[i]);
break;
} else {
root = root->right;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.