這裏是一個C++函數來從一個整數數組創建一個BST樹?
很簡單。
取第一個元素,生根。
取下一個數組元素並將其插入樹中。
爲什麼循環從i = 2開始,而不是i = 1?迭代插入二進制搜索tree.Debug C++代碼
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;
}
非常感謝你的解釋。我試了另一種方式,但它只找到root.What裏面的問題是什麼?
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;
}
它是一個二進制樹BST,或者只是一個任意? – 2012-02-20 19:28:34
for循環代碼從i = 2開始,而不是i = 1。這是一個錯字嗎? – MARK 2012-02-20 19:33:31