【发布时间】:2018-06-27 15:11:05
【问题描述】:
int* inorder(node* root)
{
//Dynamically Created array as we are required to pass array into main function
int* arr=new int[100];
int i=0;
if(root==NULL)
return 0;
inorder(root->left);
arr[i]=root->data;
i++;
inorder(root->right);
return arr;
}
我们需要使用中序遍历检查树是否为Bst。如果数组中存在的数据已排序,则为Bst。在main()中传递数组后,我们将检查数组是否已排序或不是,但 当我检查数组的内容时,它是一个垃圾值 并且对于输入树来说,树总是不是 Bst
int main()
{
node* root= newNode(6);
root->left= newNode(4);
root->right= newNode(8);
root->left->left= newNode(3);
root->left->right= newNode(5);
root->right->left= newNode(7);
root->right->right= newNode(9);
int* ptr=inorder(root);
if(is_sorted(ptr,ptr+7))
cout<<"Tree is Binary search tree: "<<endl;
else
cout<<"Tree is not a binary search tree: "<<endl;
}
【问题讨论】:
-
你有很多内存泄漏的机会,特别是因为你没有对递归调用返回的指针做任何事情。
-
至于您的问题,您分配的数组是否应该由对
inorder函数的all 调用使用和共享?然后除了它不以任何方式共享之外,你甚至不初始化它。实际上,当您可以访问std::vector时,请停止使用new[]。 -
vector
inorder(node* root) { vector v;如果(根==NULL)返回; //如果根为NULL,返回什么 inorder(root->left); v.push_back(root->data) inorder(root->right);返回 v; } -
您的数组包含垃圾也就不足为奇了。什么时候设置数组中除
arr[0]之外的任何元素的值(更准确地说,arr[i]和i等于0)?
标签: c++ arrays sorting binary-search-tree