【发布时间】:2021-06-22 20:42:32
【问题描述】:
因此,在这个问题中,我们应该从给定的预序序列构造一个 BST。 preorder[] 是大小为n 的数组,preorderIdx 表示从0开始的索引。
在constructBST()函数中,为什么我们将preorderIdx的参数作为指针传递?在函数内部,为什么我们使用*preorderIdx 而不是preorderIdx?在root->left 和root->right 中调用constructBST() 函数时,为什么我们不使用*preorderIdx?谁能给我解释一下?
#include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
struct Node* left;
struct Node* right;
Node(int val){
data = val;
left = NULL;
right = NULL;
}
};
Node * constructBST(int preorder[], int*preorderIdx, int key, int min, int max, int n){
if(*preorderIdx>=n){
return NULL;
}
Node* root = NULL;
if(key> min && key<max){
root = new Node(key);
*preorderIdx = *preorderIdx +1;
if(*preorderIdx<n){
root->left = constructBST(preorder,preorderIdx,preorder[*preorderIdx],min,key,n);
}
if(*preorderIdx<n){
root->right = constructBST(preorder,preorderIdx,preorder[*preorderIdx],key,max,n);
}
}
return root;
}
void inorder(Node* root){
if(root==NULL){
return;
}
inorder(root->left);
cout<< root->data<<" ";
inorder(root->right);
}
void printPreorder(Node* root){
if(root==NULL){
return;
}
cout<< root->data<<" ";
printPreorder(root->left);
printPreorder(root->right);
}
int main(){
int preorder[]={10,2,1,13,11};
int n =5;
int preorderIdx =0;
Node * root = constructBST(preorder,preorderIdx,preorder[0],INT_MIN,INT_MAX,n);
printPreorder(root);
}
【问题讨论】:
-
显示的代码将无法编译,因为
main()试图调用constructBST(),将int传递给预期int*。constructBST(...,preorderIdx,...)需要改为constructBST(...,&preorderIdx,...) -
将指针传递给变量在 C 中常用来模拟按引用传递。您可能想投资some good C++ books 以正确学习 C++,而不是使用所谓的“竞争”网站。此类网站上使用的代码通常从糟糕到非常糟糕(那种糟糕到会让代码的作者几乎失业)。
-
是的,我忘了添加 &
-
你使用的是什么参考,告诉你使用
<bits/stdc++>。这不是标准的。你应该得到一个不同的参考。
标签: c++ pointers binary-search-tree