[英]iteratively insert into a binary search tree.Debug C++ code
Here is a c++ function to create a BST tree from an array of integers? 这是一个C ++函数,用于从整数数组创建BST树?
It's simple. 这很简单。
Take first element ,make root. 以第一个元素为根。
Take next array element and insert it into the tree. 获取下一个数组元素并将其插入树中。
Why is the loop starting from i=2 and not i=1?? 为什么循环从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;
}
Thanks a lot for explaining it.I tried it another way but it only finds the root.What's the problem in it? 非常感谢您对它的解释。我尝试了另一种方法,但它只能找到根,这是什么问题?
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;
}
Because in the first iteration of the loop the while
condition is not true because the root node has no child nodes. 因为在循环的第一次迭代中,
while
条件不成立,因为根节点没有子节点。
while(!(root->left==NULL && root->right==NULL)
for i=1 the left and the right node are NULL and the left node is populated at the end of the first iteration. 对于i = 1,左侧和右侧节点为NULL,并且左侧节点在第一次迭代结束时填充。
When trying to find the point of insertion, 当试图找到插入点时,
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;
}
you only stop if both children are NULL
, so at some point or other, you will set root
to NULL
. 仅当两个子项都为
NULL
时才停止,因此在某些时候,您将root
设置为NULL
。 Consider the array begins with [5, 3, 6, ... ]
. 考虑数组以
[5, 3, 6, ... ]
开头。 You start with 你开始
NULL <- node(5) -> NULL
node(3) <- node(5) ->NULL
and then try to insert the 3. Since not both children are NULL
, the while
loop runs 然后尝试插入3。由于不是两个孩子都为
NULL
,所以while
循环运行
if (5 > 7) // false
root = root->left;
else
root = root->right; // now root == NULL, oops
and the controlling condition is checked anew 并重新检查控制条件
while(!(NULL->left == NULL && NULL->right == NULL))
segfault likely here, undefined behaviour invoked. segfault可能在这里调用未定义的行为。
You should do something like 你应该做类似的事情
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.