[英]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.