[英]Same test case but different output on codeblocks and Ideone
好的,我最近開始嘗試與樹相關的問題,有一個簡單的代碼可以找到二叉搜索樹的高度。 在我的CodeBlocks系統上,它可以正常工作,但是當我在在線IDE上進行編譯時,它會提供不同的輸出(每次2個)。 例如在代碼塊上
4
2 1 3 4
給出輸出3
但在在線IDE(Ideone,Codechef,Hackerearth)上
4
2 1 3 4
給出輸出2
不僅這個測試用例,而且所有測試用例都在線給出輸出2。 請幫忙!!
編碼:
#include<iostream>
#include<cstdlib>
using namespace std;
typedef struct node
{
struct node* left;
long value;
struct node* right;
}tnode;
tnode* insertnode(long,tnode*);
tnode* createnode(long);
int height(tnode*);
void preorder(tnode*);
int main()
{
int n,i;
cin>>n;
long input[n];
for(i=0;i<n;i++)
{
cin>>input[i];
}
tnode *root=(tnode*)malloc(sizeof(tnode));
root=NULL;
//cout<<"HI"<<endl;
root=insertnode(input[0],root);
for(i=1;i<n;i++)
{
insertnode(input[i],root);
}
//preorder(root);
cout<<height(root)<<endl;
return 0;
}
tnode* insertnode(long value,tnode* node)
{
if(node==NULL)
{
return createnode(value);
}
else if(value<node->value)
{
node->left=insertnode(value,node->left);
}
else if(value>node->value)
{
node->right=insertnode(value,node->right);
}
}
tnode* createnode(long value)
{
tnode* temp=(tnode*)malloc(sizeof(tnode));
temp->value=value;
temp->left=temp->right=NULL;
return temp;
}
int height(tnode* node)
{
int lht,rht;
if(node==NULL)
{
return 0;
}
else
{
lht=height(node->left);
rht=height(node->right);
if(lht>=rht)
{
return lht+1;
}
else
{
return rht+1;
}
}
}
void preorder(tnode* temp)
{
if(temp!=NULL)
{
cout<<temp->value<<" ";
preorder(temp->left);
preorder(temp->right);
}
}
預先謝謝您,如果我在提問時犯了任何錯誤,對不起。
主要問題是insertnode
。 它被聲明返回一個tnode *
,但並非總是如此:它確實return createnode(value);
如果node
為NULL
,但在所有其他情況下均不返回值。 您的編譯器應該對此大聲抱怨。
從而:
node->right=insertnode(value,node->right);
如果最初為NULL
則此行將新節點分配給node->right
。 但是,如果它不是NULL
,則node->right
會被垃圾值覆蓋。
其他事宜:
您在這里有內存泄漏:
tnode *root=(tnode*)malloc(sizeof(tnode)); root=NULL;
malloc
返回的指針丟失,因為第二行用NULL
覆蓋它。
有中沒有點typedef
在C ++中手動荷蘭國際集團結構類型。 當您struct node { ... };
,您會自動獲得兩個已定義的名稱: struct node
和node
。 無需typedef
。
不建議在C ++中使用malloc
。 new
(或new []
)會更好; 更好的是某種智能指針; 最好是一些為您處理內存管理的容器類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.