2014-09-30 74 views
1

這是我的程序,但我不知道如何在數組中顯示二叉搜索樹結果(一維)。我使用隨機作爲輸入。如何在數組中顯示二分搜索樹結果?請幫幫我。如何在數組中顯示二叉搜索樹結果?

#include<iostream> 
#include<algorithm> 

using namespace std; 

struct BstNode{ 
    int data; 
    BstNode* left; 
    BstNode* right; 
}; 

BstNode* GetNewNode(int data){ 
    BstNode* newNode = new BstNode(); 
    newNode->data = data; 
    newNode->left = newNode->right = NULL; 
    return newNode; 
} 

BstNode* Insert(BstNode* root, int data){ 
    if(root == NULL){ 
     root = GetNewNode(data); 
    } 
    else if(data <= root->data){ 
     root->left = Insert(root->left,data); 
    } 
    else{ 
     root->right = Insert(root->right,data); 
    } 
    return root; 
} 


int main(){ 
    int x, i, n, data; 
    BstNode* root = NULL; 
    cout<<"The number of data : ";cin>>n; 
    for (i=1;i<=n;i++) { 
     data=(rand()%100+1); 
     cout<<data<<" "; 
     Insert(root,data); 
    } 
} 
+0

你知道C++有類,對吧? – sje397 2014-09-30 04:42:49

+0

也許你想谷歌'堆排序'? – sje397 2014-09-30 04:43:25

+0

我們還沒有在C++中使用類。 – user119420 2014-09-30 04:49:27

回答

0

我猜OP正在尋找填充一個數組與BST的元素,如在有序遍歷中所觀察到的。如果是這樣,我們可以嘗試如下所示。

void 
fillArrayInorder(BstNode const * pCurr, int * pArr, int & arrIdx) { 
    if(pCurr) { 
     fillArrayInorder(pCurr->left, pArr, arrIdx); 
     pArr[ arrIdx++ ] = pCurr->data; 
     fillArrayInorder(pCurr->right, pArr, arrIdx); 
    } 
} 

稱其爲

int arr[ MAX_ELEMS ]; 
int arrIdx = 0; 
fillArrayInorder(root, & arr, arrIdx); 

注:而不是原始陣列的,它可能是更好地使用vector及其push_back()方法,使得其長度和索引更新的複雜性是沒有必要應用程序代碼。